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.

2

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

can't we do this without Underscore or Lo-Dash?
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]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.