Home > Enterprise >  How to unite 2 arrays with objects without repetition in JS
How to unite 2 arrays with objects without repetition in JS

Time:01-24

I have 2 objects.

const obj1 = [{a: 1, b: 2}, {a: 2, b: 4}, {a: 8, b: 3}];
const obj2 = [{a: 1, b: 2}, {a: 3, b: 4}, {a: 8, b: 3}, {a: 7, b: 3}];

And I want to unite them in one but without repetitions. the result should be obj3 = [{a: 1, b: 2}, {a: 2, b: 4}, {a: 3, b: 4}, {a: 8, b: 3}, {a: 7, b: 3}];

const obj3 = obj1.map((item) => obj2.filter((i) => i !== item));

is not working.

CodePudding user response:

The problem is you are mapping over an array, so basically you will do the filter every obj1.length time.

In term of the filter, filter will remove all the same item in obj1 and you will only get the not duplicate item in obj2, you could group them.

Another good solution I would suggest is to concat the two array and filter it.

const obj1 = [{a: 1, b: 2}, {a: 2, b: 4}, {a: 8, b: 3}];
const obj2 = [{a: 1, b: 2}, {a: 3, b: 4}, {a: 8, b: 3}, {a: 7, b: 3}];
let obj3 = obj1.concat(obj2)

let obj4=obj3.filter((item,index) => obj3.indexOf(item) === index)
console.log(obj4)

CodePudding user response:

You can always try to loop through the first one and loop through the second one for each entry, checking for repetition.

CodePudding user response:

It's handy to use the lodash libray to handle array operations like the one you're asking about: https://lodash.com/docs/4.17.15#union

var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];

_.unionWith(objects, others, _.isEqual);
// => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }]

It's easy to add the lodash library to your code. You can download and save the lodash.js file here: https://lodash.com/, or just use a url from a CDN and include with your other scripts/script tags: https://cdnjs.com/libraries/lodash.js

  •  Tags:  
  • Related