Removing duplicates from JS array

I have the following JS array:

var items=[
    { id: 1, name: 'aa' },
    { id: 1, name: 'bb' },
    { id: 2, name: 'cc' },
    { id: 1, name: 'dd' }
];

      

I want to convert it to the following.

var items=[
    { id: 1, name: 'dd' },
    { id: 2, name: 'cc' }
];

      

How can I do this using JavaScript?

+3


source to share


4 answers


We could do it quite simply by just looping over it. For each element, assign its place in a new array corresponding to its identifier. Previous identifiers are overwritten, so only the last one is saved.



var items=[
    { id: 1, name: 'aa' },
    { id: 1, name: 'bb' },
    { id: 2, name: 'cc' },
    { id: 1, name: 'dd' }
], newItems = [];
for (var i =0;i<items.length;i++){
    newItems[items[i].id - 1] = items[i];
}
alert(JSON.stringify(newItems));
      

Run codeHide result


+1


source


Try the following:



items = items.reverse().filter((function() {
    var existing = {};
    return function(item) {
        if(existing[item.id]) {
            return false;
        }
        existing[item.id] = true;
        return item;
    }
}()));

      

0


source


This should do what you want:

var items = [
    { id: 1, name: 'aa' },
    { id: 1, name: 'bb' },
    { id: 2, name: 'cc' },
    { id: 1, name: 'dd' }
];

function removeDupIds(items){
    var result  = [],
        uniqIds = {},
        i       = 0,
        l       = items.length;

    for(; i<l; i++){
        uniqIds[items[i].id] = items[i].name;
    }

    for(var k in uniqIds){
        result.push({id: k, name: uniqIds[k]});
    }
    return result;
}

console.log(removeDupIds(items));

      

0


source


Using underscore it would be simple

_.uniq(items.reverse(), function(i1, i2) { return i1.id === i2.id; }))

      

Usually _.uniq

removes the same elements, but we can pass it a second parameter that defines the function used to determine if two elements are considered the same.

Required items.reverse()

because the OP seems to want the last element to take precedence.

0


source







All Articles