0

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}]

Jeesmon Joy
  • 196
  • 1
  • 2
  • 16
  • what would happen, if it occurs multiple time? – Suman Majhi Mar 28 '22 at 07:03
  • @SumanMajhi only keep the last one – Jeesmon Joy Mar 28 '22 at 07:15
  • Does this answer your question? [How to remove all duplicates from an array of objects?](https://stackoverflow.com/questions/2218999/how-to-remove-all-duplicates-from-an-array-of-objects) – Prit Hirpara Mar 28 '22 at 07:19
  • This should be sufficient: `Object.values(array.reduce((acc, itm) => ({...acc, [itm.id]: {...itm}}), {}));`. It iterates using `.reduce`, removes duplicates by keeping last element based on `id`, creates an intermediate object (resulting from `.reduce`) and gets the `Object.values` to get an array back. All of it - in one line. :-) PS: It uses shallow copy (by `...` spread-operator) so changes to the original array will not impact the result generated. – jsN00b Mar 28 '22 at 07:21

4 Answers4

3

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)
malarres
  • 2,941
  • 1
  • 21
  • 35
  • i want the last one, not the second one – Jeesmon Joy Mar 28 '22 at 07:16
  • Why not this @malarres: `Object.values(array.reduce((acc, itm) => ({...acc, [itm.id]: {...itm}}), {}));`. This should give the array with keeping last element in case of duplicate `id`s. – jsN00b Mar 28 '22 at 07:20
1

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);
YuTing
  • 6,555
  • 2
  • 6
  • 16
1

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}));
PedroZorus
  • 661
  • 1
  • 6
  • 21
0

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)
Yahya Altintop
  • 204
  • 2
  • 12