-2

I have an array of objects:

[{
  id: 1,
  name: 'kitten'
}, {
  id: 2,
  name: 'kitten'
},{
  id: 3,
  name: 'cat
}]

How do I remove the second kitten? Sorting into an array of names doesn't work, because I can't know if I am deleting id 1 or or id 2. So, I'm not quite sure how to do this.

RichLitt
  • 352
  • 1
  • 3
  • 13

3 Answers3

1

You can use an additional hash-map to store names found so far. When you process a next object if it's name is already in the hash-map it is a duplicate and you can remove it.

var duplicates = {};
for (var i = 0; i < array.length) {
    var obj = array[i];

    if (! duplicates[obj.name]) {
        duplicates[obj.name] = 1;
        i++;
    } else {
        array.splice(i, 1);
    }
}
Ivan Mushketyk
  • 8,107
  • 7
  • 50
  • 67
  • Do you have an example piece of code I could look at, for that? I know that this is possible in other languages, I just haven't encountered hash maps before in JS. – RichLitt Jun 16 '15 at 11:13
0

there is the lodash library. You could use the uniq

var array = [{
  id: 1,
  name: 'kitten'
}, {
  id: 2,
  name: 'kitten'
},{
  id: 3,
  name: 'cat'
}];


var asd = _.uniq(array,'name');

console.log(asd);

Gives an output:

[ { id: 1, name: 'kitten' }, { id: 3, name: 'cat' } ]

as it written in the documentation "only the first occurence of each element is kept".

cs04iz1
  • 1,737
  • 1
  • 17
  • 30
  • Yeah, I thought of that too. The issue is that I need to find the ID of the excluded item in order to delete it through an API. Not sure how to get that. Perhaps a set function that shows me the difference? – RichLitt Jun 16 '15 at 11:19
  • 1
    yes you could do that. use the difference function of lodash, doing the following var asd = _.uniq(array,'name'); console.log(asd); var dif = _.difference(array,asd); console.log(dif); – cs04iz1 Jun 16 '15 at 11:35
0

    var arr =[{
      id: 1,
      name: 'kitten'
    }, {
      id: 2,
      name: 'kitten'
    },{
      id: 3,
      name: 'cat'
    }];
    var results = [];
    var idsSeen = {}, idSeenValue = {};
    for (var i = 0, len = arr.length, name; i < len; ++i) {
        name = arr[i].name;
        if (idsSeen[name] !== idSeenValue) {
            results.push(arr[i]);
            idsSeen[name] = idSeenValue;
        }
    }
    console.log(results);
ozil
  • 6,930
  • 9
  • 33
  • 56