Javascript - merging a two-dimensional array with a unique result

I have this two arrays in javascript

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

I want to combine this array with a unique value as follows:

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

I tried the function concat, but it does not work properly.

+3
source share
2 answers

you know, I'm sure others can do something more eloquent, but here is my hit on it with 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]]);
    })

it's the same thing, 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]]
+1
source

Do you use nested arrays to emulate an object that preserves order? If so, then write a container object that handles the sort for you.

, Underscore Lo-Dash:

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

[1] != [1], . JSON.stringify - () .

+2

All Articles