简体   繁体   中英

Underscore.js get an array of unique objects

I have 2 arrays of objects. There are duplicates between the arrays. I want to merge them into 1 array of all unique objects (so no duplicates).

How can I do this by comparing the "id" of each object?

Underscore.js has a method called _.uniq() . It looks to be correct, but I can't get the syntax for the "iterator" argument correct.

var firstArray = [{ id: 1, name: "foo"}, { id: 2, name: "bar" }];
var secondArray = [{ id: 2, name: "boop" }, { id: 3, name: "baz" }];

firstArray.push(secondArray);
var myUniqueArray = _.uniq(firstArray, false, ???);

myUniqueArray // [{ id: 1, name: "foo"}, { id: 2, name: "bar" }, { id: 3, name: "baz" }];

You should be able to achieve this with _.uniq method used with second parameter of the property name to be used to filter items:

 var firstArray = [{ id: 1, name: "foo"}, { id: 2, name: "bar" }]; var secondArray = [{ id: 2, name: "boop" }, { id: 3, name: "baz" }]; var result = _.uniq(firstArray.concat(secondArray), 'id'); alert(JSON.stringify(result, null, 4)); 
 <script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script> 

The following should do it:

var myUniqueArray = _.uniq(firstArray.concat(secondArray), false, function (obj) {
    return obj.id;
});

The iteratee here will produce a value on which uniqueness is checked, in this case the id property value.

Here's a JSFiddle .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM