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"}
    ]
3
  • Is the comparison always based on one key (column in this case)? Commented Sep 3, 2018 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? Commented Sep 3, 2018 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. Commented Sep 3, 2018 at 13:59

1 Answer 1

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);

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

3 Comments

It works perfectly Ankit, thank you so much ! JS looks really easy when other people do it, but I figured out harder way that it is not. You are the best !
It makes me to wait 10 minutes before making the answer :) do not worry I am look at the clock
@Milosh oh i see. cool :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.