0

I would like to loop through two arrays, compare them and create new array that will contain objects from both arrays but omit ones that are the same: Code below explains how end result should look like. Thank you.

Array1 = [
    {"column": "brand_name1"},
    {"column": "brand_name2"}
    ]

    Array2 = [
    {"column": "brand_name1"},
    {"column": "brand_name3"}
    ]

    And result should be something like

    Array3 = [
    {"column": "brand_name1"},
    {"column": "brand_name2"},
    {"column": "brand_name3"}
    ]
zawarudo
  • 1,907
  • 2
  • 10
  • 20
  • Is the comparison always based on one key (`column` in this case)? – lealceldeiro Sep 03 '18 at 13:56
  • 1
    You want the values that are the same to be omited, but you have {"column": "brand_name1"} in your result array. Do you mean instead that you don't want duplicates? – Philzax Sep 03 '18 at 13:56
  • @Philzax Yes that is correct, if all properties match ( or in this snippet one ), it should only appear once in new array. Yes, in new array there should be no duplicates. – zawarudo Sep 03 '18 at 13:59

1 Answers1

2

Here is a O(n) solution for getting the unique array from the two array of objects.

var Array1 = [{
    "column": "brand_name1"
  },
  {
    "column": "brand_name2"
  }
]

var Array2 = [{
    "column": "brand_name1"
  },
  {
    "column": "brand_name3"
  }
]

var newArray = [...Array1, ...Array2];
var tempObj = {};
newArray.forEach((item) => {
  var value = Object.values(item)[0];
  if(!tempObj[value]){
    tempObj[value] = item;
  }
});
var Array3 = Object.values(tempObj);
console.log(Array3);
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62