I have an array with objects:

let arr = [ { name: 'Jahn', email: 'john@test.com' }, { name: 'Bob', email: 'bob@test.com' } ] 

I need to add objects. How can I add only unique objects. For example, how can you add only unique objects from such an array?

 let arr2 = [ { name: 'Max', email: 'max@test.com' }, { name: 'Bob', email: 'bob@test.com' }, { name: 'Jahn', email: 'john@test.com' }, { name: 'Julie', email: 'julie@test.com' } ] 

This should result in:

 let result = [ { name: 'Jahn', email: 'john@test.com' }, { name: 'Bob', email: 'bob@test.com' }, { name: 'Max', email: 'max@test.com' }, { name: 'Julie', email: 'julie@test.com' } ] 

The unique property of the object is email

  • why not use email as a key, for example, let users = {'example@gmail.com': {....}}; ? or in the context of your problem the current solution does not fit? - Arendach
  • I already have a ready-made array and I need to add users that come with api to it - dev_jun

2 answers 2

Well, somehow, it turned out to be a rather long example, everything could have been written down with one function, but I divided it into as many as 3. My goal was to show the algorithm and think nicely you can.

 let arr1 = [ { name: 'Jahn', email: 'john@test.com' }, { name: 'Bob', email: 'bob@test.com' } ]; let arr2 = [ { name: 'Max', email: 'max@test.com' }, { name: 'Bob', email: 'bob@test.com' }, { name: 'Jahn', email: 'john@test.com' }, { name: 'Julie', email: 'julie@test.com' } ]; function array2object(array, field){ let res = {}; for(let i in array) if (!(i in res)) res[array[i][field]] = array[i]; return res; } function object2array(object) { let res = []; for(let i in object) res.push(object[i]); return res; } function union(arr1, arr2) { for (let i in arr2) if (!(i in arr1)) arr1[i] = arr2[i]; return arr1; } // первый параметр это сам массив а второй уникальное поле // которое будет ключом let obj1 = array2object(arr1, 'email'); let obj2 = array2object(arr2, 'email'); let result = object2array(union(obj1, obj2)); console.log(result); 

    Here is another option.

     const arr = [{ name: 'Jahn', email: 'john@test.com' }, { name: 'Bob', email: 'bob@test.com' } ] const arr2 = [{ name: 'Max', email: 'max@test.com' }, { name: 'Bob', email: 'bob@test.com' }, { name: 'Jahn', email: 'john@test.com' }, { name: 'Julie', email: 'julie@test.com' } ] function addUnique(arrTarget, arrSource, field) { const res = arrTarget.splice(); arrSource.forEach(f => { if (!res.some(s => s[field] === f[field])) res.push(f); }); return res; } const res = addUnique(arr, arr2, 'email'); console.log(res);