How to usefilter() and some() in Javascript
- The
some()
method is used to check if there is any object inarray1
with the sameid
as the current object inarray2
. - The
filter()
method is applied toarray2
to only include objects that are not present inarray1
(based on theid
property). - The final array,
resultArray
, contains unique objects from both arrays.
Example: This example shows the implementation of the above-explained approach.
JavaScript
const array1 = [{ id: 1, name: 'John' }, { id: 2, name: 'Jane' }]; const array2 = [{ id: 2, name: 'Jane' }, { id: 3, name: 'Doe' }]; const mergedArray = array2.filter(item2 => !array1.some(item1 => item1.id === item2.id) ); const resultArray = [...array1, ...mergedArray]; console.log(resultArray); |
Output
[ { id: 1, name: 'John' }, { id: 2, name: 'Jane' }, { id: 3, name: 'Doe' } ]
How to Merge two Different Arrays of Objects with Unique Values only in JavaScript ?
Merging two arrays of objects with unique values is a common task in JavaScript. This operation involves combining the elements of two arrays while ensuring that each resulting object has a unique identifier. We will explore various approaches to merging two arrays of objects with unique values.
These are the following approaches:
Table of Content
- Using concat() and filter()
- Using reduce()
- Using Map and Set
- Using filter() and some()
- Using filter() and Map and has()
Contact Us