I am trying to remove duplicate from an array of object in Javascript. Below is the code which doesnot work, it is creating Array of map of size 4.
let arr = [{id: 32, name: 'Name1', age: 88},
{id: 33, name: 'Name2', age: 88},
{id: 32, name: 'Name3', age: 88},
{id: 1, name: 'Sam', age: 88},
{id: 33, name: 'Name2', age: 88},
{id: 2, name: 'Tom', age: 88}
];
console.log(arr)
let mp1 = new Map();
let uniqueElements = arr.map( obj => mp1.set(obj.id, obj))
console.log(uniqueElements);
Below snippet may be one possible implementation to achieve the desired objective:
const discardDupeIdElements = arr => (
Object.values(
arr.reduce(
(fin, itm) => ({
...fin,
[itm.id]: itm
}), {}
)
)
);
var origArr = [{
id: 32,
name: 'Name1',
age: 88
},
{
id: 33,
name: 'Name2',
age: 88
},
{
id: 32,
name: 'Name3',
age: 88
},
{
id: 1,
name: 'Sam',
age: 88
},
{
id: 33,
name: 'Name2',
age: 88
},
{
id: 2,
name: 'Tom',
age: 88
}
];
console.log(discardDupeIdElements(origArr));
Note
This will always keep the last element of a set of duplicates and ignore all earlier ones. Such as for id 32, it will keep the element with name = Name3 and discard Name2.
Fixing the OP's code:
const arr = [{id: 32, name: 'Name1', age: 88},
{id: 33, name: 'Name2', age: 88},
{id: 32, name: 'Name3', age: 88},
{id: 1, name: 'Sam', age: 88},
{id: 33, name: 'Name2', age: 88},
{id: 2, name: 'Tom', age: 88}
];
// console.log(arr);
// commented-out for easier viewing of the output
const mp1 = new Map(); // declared a map
arr.forEach(obj => mp1.set(obj.id, obj));
// used .forEach to iterate through the array
// and update the map
const uniqueElements = [...mp1.values()];
// used spread operator to extract
// the values of the map into an array
console.log(uniqueElements);
// console.log the unique elements
Note
Where possible, used const rather than let.
map returns the new array with the same length of the calling array
For accumulated value (here is mp1), you should use reduce
let uniqueElements = arr.reduce(
(mp1, obj) => mp1.set(obj.id, obj),
new Map()
)
let arr = [
{ id: 32, name: 'Name1', age: 88 },
{ id: 33, name: 'Name2', age: 88 },
{ id: 32, name: 'Name3', age: 88 },
{ id: 1, name: 'Sam', age: 88 },
{ id: 33, name: 'Name2', age: 88 },
{ id: 2, name: 'Tom', age: 88 },
]
console.log(arr)
let uniqueElements = arr.reduce((mp1, obj) => mp1.set(obj.id, obj), new Map())
console.log(uniqueElements)