pardon my English , i want to remove first element of an array of object if it occur twice
here is the array=[{id:34,value:45}, {id:23,value:35}, {id:34,value:28}]
i want to remove first element because third element's id is same as first element
output should be array=[{id:23,value:35}, {id:34,value:28}]
CodePudding user response:
This will give you an array with the last value for duplicated elements, in preserved order. If you want exactly the 2nd one you need an extra flag
array=[{id:34,value:45}, {id:23,value:35}, {id:34,value:28}]
const obj = array.reduce ( (acc,cur,index) => {
acc[cur.id] = {index:cur};
return acc;
},{});
const output = Object.values(obj).sort( (a,b) => a.index - b.index).map( ({index:val}) => val )
console.log(output)
CodePudding user response:
A solution using ES6
const array = [
{ id: 34, value: 45 },
{ id: 23, value: 35 },
{ id: 34, value: 28 },
];
const convertToArray = array.map(({ id, value }) => [id, value]);
const convertToSet = Object.fromEntries(convertToArray);
const revertAsCleanedArray = Object.entries(convertToSet);
const cleanedArrayOfObjects = revertAsCleanedArray.map(([id, value]) => ({id, value}));
CodePudding user response:
Get all unique values in a JavaScript array
let arr = [{id:34,value:45}, {id:23,value:35}, {id:34,value:28}]
var unique = arr.reverse().filter((v, i, a) => a.map(e => e.id).indexOf(v.id) === i);
console.log(unique);
CodePudding user response:
This can help you
let array = [{id:34,value:45}, {id:23,value:35}, {id:34,value:28}]
let result = array.filter((x,i) => array.findLastIndex(y => y.id == x.id) == i)
console.log(result)