This solution does not specifically pertain to angular2/typescript; rather, it utilizes ES6 functionality.
To remove duplicates from an array, you can use the uniq
function from lodash (https://lodash.com/docs/4.17.4#uniq). Here's an example of how to apply it:
const arrA = [1, 2, 3, 4];
const arrB = [3, 4, 5, 6];
const arr = _.uniq([...arrA, ...arrB])
// Result: [1, 2, 3, 4, 5, 6]
If dealing with nested objects, consider using uniqBy
or uniqWith
, which are also part of lodash.
const arrA = [{id: 1, n: 'e'}, {id: 2, n: 'z'}];
const arrB = [{id: 2, n: 'z'}, {id: 3, n: 'c'}];
const arr = _.uniqBy([...arrA, ...arrB], 'id')
// Result: [{id: 1, n: 'e'}, {id: 2, n: 'z'}, {id: 3, n: 'c'}]
It is essential to have a unique identifier (like id
) to identify and eliminate duplicates accurately.
[EDIT] If lacking a unique identifier and aiming to deduplicate based on entire objects, you can achieve this as shown below:
const arrA = [{a: 'a'}, {b: 'b'}];
const arrB = [{b: 'b'}, {c: 'c'}];
const arr = _.uniqBy([...arrA, ...arrB], JSON.stringify)
// Result: [{a: 'a'}, {b: 'b'}, {c: 'c'}]
This method converts objects into strings for comparison, but be cautious with performance implications when working with large objects/arrays. It is advisable to have a unique identifier whenever possible.