开发者

jQuery - Finding Distinct Values in Object Array

开发者 https://www.devze.com 2023-04-04 21:50 出处:网络
I\'ve got an array of objects where each object has fields like title,开发者_StackOverflow description, family, etc.How can I perform a jQuery operation that grabs all objects in this array with a uni

I've got an array of objects where each object has fields like title,开发者_StackOverflow description, family, etc. How can I perform a jQuery operation that grabs all objects in this array with a unique family name - similar to SQL's DISTINCT clause?


You could do:

var array = [{
    familyName: "one"},
{
    familyName: "two"},
{
    familyName: "one"},
{
    familyName: "two"}];

var dupes = {};
var singles = [];

$.each(array, function(i, el) {

    if (!dupes[el.familyName]) {
        dupes[el.familyName] = true;
        singles.push(el);
    }
});

Singles is an array with only DISTINCT objects

EDIT - i have blogged about this and given a more elaborate answer http://newcodeandroll.blogspot.it/2012/01/how-to-find-duplicates-in-array-in.html

0

精彩评论

暂无评论...
验证码 换一张
取 消