最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

JavaScript Object Array: Removing objects with duplicate properties - Stack Overflow

programmeradmin0浏览0评论

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.

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.

Share Improve this question edited Sep 17, 2015 at 15:55 opticon asked Sep 17, 2015 at 15:49 opticonopticon 3,5945 gold badges40 silver badges66 bronze badges 1
  • 1 possible duplicate of Remove duplicates from an array of objects in javascript – Marcos Pérez Gude Commented Sep 17, 2015 at 15:52
Add a comment  | 

6 Answers 6

Reset to default 10

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

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

If you use underscore, you can use the _uniq method

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

_.uniq(data, function(d){ return d.ID });

Produces a duplicate-free version of the array, using === to test object equality. In particular only the first occurence of each value is kept. If you know in advance that the array is sorted, passing true for isSorted will run a much faster algorithm. If you want to compute unique items based on a transformation, pass an iteratee function.

Source: http://underscorejs.org/#uniq

Can use es6 Map collection mix with reduce

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

const uniqItems = [...items.reduce((itemsMap, item) =>                                                                   
      itemsMap.has(item.id) ? itemsMap : itemsMap.set(item.id, item)
    , new Map()).values()]

console.log(uniqItems);

Using findIndex should be the simplest solution.

array.filter((elem, index, arr) => arr.findIndex(e => e.id === elem.id) === index) 

You can simply filter the array, but you'll need an index of existing IDs that you've already used...

    var ids = [];
    var ar = [
        { id: 1, name: "Bob" },
        { id: 1, name: "Donald" },
        { id: 2, name: "Daryl" }
    ];
    ar = ar.filter(function(o) {
        if (ids.indexOf(o.id) !== -1) return false;
        ids.push(o.id);
        return true;
    });
    console.log(ar);

Here's some documentation on filter()...

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

发布评论

评论列表(0)

  1. 暂无评论