3

I have this two array in Javascript

var array1 = [
              ["Tech & Digital", 124],
              ["Stationery", 100]
             ]
var array2 = [
              ["Gift Item", 125],
              ["Stationery", 100]
             ]

I want to merge this 2 array with unique value as follows,

            [
              ["Tech & Digital", 124],
              ["Stationery", 100],
              ["Gift Item", 125]
             ]

I tried concat function, but it's not working as expected.

Lee Gary
  • 2,221
  • 2
  • 18
  • 37
iLaYa ツ
  • 3,767
  • 2
  • 26
  • 45

2 Answers2

2

Are you using nested arrays to emulate an object that preserves order? If so, then write a container object that handles the sorting for you.

If not, you can use Underscore or Lo-Dash:

_.uniq(_.union(array1, array2), false, JSON.stringify)

Since [1] != [1], you have to compare them manually. JSON.stringify is one (hacky) way of doing it.

Blender
  • 257,973
  • 46
  • 399
  • 459
1

you know, I am sure others can make something a bit more eloquent but here is my stab at it using jquery.

var array1 = [
              ["Tech & Digital", 124],
              ["Stationery", 100]
             ]
var array2 = [
              ["Gift Item", 125],
              ["Stationery", 100]
             ]
var obj = {}
jQuery.map(array1.concat(array2),function(i,v){return obj[i[0]] = i[1] })
array1 = jQuery.map(obj, function(j,w){
       return [].concat([[w,j]]);
    })

this is the same, but modified for a non-library solution. pre ECMAScript5.

var arr = array1.concat(array2), obj = {};
for(var i = 0; i < arr.length; i++){
    obj[arr[i][0]] = arr[i][1];
}
array1 = function() {
      var arr = [];
      for(key in obj){
       arr.push([[key,obj[key]]])
      }
      return arr;
}()

both return:

[["Tech & Digital", 124], ["Stationery", 100], ["Gift Item", 125]]
james emanon
  • 8,958
  • 7
  • 40
  • 66