Get the last values from the array having same ids:
Input:
[{id:1,name:"Java"},{id:1,name:"JavaScript"},{id:1,name:"Python"},{id:1,name:"C++"},{id:2,name:"C"},{id:2,name:"Ruby"},{id:2,name:"Php"}]
Required Output:
[{id:1,name:"C++"},{id:2,name:"Php"}]
So, I have tried doing
array?.reverse().filter( (ele, ind) => ind === array.findIndex((elem) => elem?.id === ele?.id))
but it gives me the output [{id:1,name:"Java"},{id:2,name:"C"}]
You can use a straightforward Array.reduce() for this purpose, creating a map keyed on id. We'll use Object.values() to turn our map into an array:
const input = [{id:1,name:"Java"},{id:1,name:"JavaScript"},{id:1,name:"Python"},{id:1,name:"C++"},{id:2,name:"C"},{id:2,name:"Ruby"},{id:2,name:"Php"}];
const result = Object.values(input.reduce((acc, cur) => {
acc[cur.id] = cur;
return acc;
}, {}))
console.log('Result:', result)
One could also use a Map and reduce again:
const input = [{id:1,name:"Java"},{id:1,name:"JavaScript"},{id:1,name:"Python"},{id:1,name:"C++"},{id:2,name:"C"},{id:2,name:"Ruby"},{id:2,name:"Php"}];
const result = [...input.reduce((acc, cur) => {
return acc.set(cur.id, cur);
}, new Map()).values()];
console.log('Result:', result);