Home > Blockchain >  Remove all objects with equal values from array of objects, excepted every first object
Remove all objects with equal values from array of objects, excepted every first object

Time:07-27

I need to leave in the array only objects with unique name values. Filter first unique objects. The rest must be removed. There's the array example:

var arr = [
  {name: "a", value: "1"},
  {name: "a", value: "2"},
  {name: "b", value: "1"},
  {name: "b", value: "2"},
  {name: "a", value: "3"},
  {name: "b", value: "3"},
  {name: "a", value: "4"},
  {name: "b", value: "4"},
  {name: "c", value: "5"},
]

I need to get something like that:

var arr = [
  {name: "a", value: "1"},
  {name: "b", value: "1"},
  {name: "c", value: "5"},
]

Would be grateful for the best way, using ES6 and newer

CodePudding user response:

Use reduce and Object.values to only accumulate the first of any given name

var arr = [
  {name: "a", value: "1"},
  {name: "b", value: "1"},
  {name: "a", value: "2"},
  {name: "b", value: "2"},
  {name: "a", value: "3"},
  {name: "b", value: "3"},
  {name: "a", value: "4"},
  {name: "b", value: "4"},
  {name: "c", value: "5"},
]

const result = Object.values(
    arr.reduce((acc, i) => (acc[i.name] ??= i, acc), {})
);

console.log(result);

  • Related