Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Object Array: Removing objects with duplicate properties

I have an array of objects:

[
  { id: 1, name: "Bob" },
  { id: 1, name: "Donald" },
  { id: 2, name: "Daryl" }
]

I'd like to strip out objects with duplicate Ids, leaving an array that would look like this:

[
  { id: 1, name: "Bob" },
  { id: 2, name: "Daryl" }
]

I don't care which objects are left, as long as each ID is unique. Anything in Underscore, maybe, that would do this?

Edit: This is not the same as the duplicate listed below; I'm not trying to filter duplicate OBJECTS, but objects that contain identical IDs. I've done this using Underscore - I'll post the answer shortly.

like image 851
opticon Avatar asked Aug 28 '26 22:08

opticon


2 Answers

You can use reduce and some to good effect here:

var out = arr.reduce(function (p, c) {

  // if the next object's id is not found in the output array
  // push the object into the output array
  if (!p.some(function (el) { return el.id === c.id; })) p.push(c);
  return p;
}, []);

DEMO

like image 177
Andy Avatar answered Aug 30 '26 13:08

Andy


the es6 way

function removeDuplicates(myArr, prop) {
    return myArr.filter((obj, pos, arr) => {
        return arr.map(mapObj => mapObj[prop]).indexOf(obj[prop]) === pos
    })
}

Test it

let a =[
      { id: 1, name: "Bob" },
      { id: 1, name: "Donald" },
      { id: 2, name: "Daryl" }
    ]

    console.log( removeDuplicates( a, 'id' ) )

    //output [
      { id: 1, name: "Bob" },
      { id: 2, name: "Daryl" }
    ]
like image 23
angry kiwi Avatar answered Aug 30 '26 12:08

angry kiwi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!