0

I have a structure like this:

var arr = [
    {
        title: 'anchorman'
    },
    {
        title: 'happy gilmore'
    },
    {
        title: 'anchorman'
    }
]

Now what would i have to do to end up with an array like this:

var arr = [
        {
            title: 'anchorman'
        }
]

So it not only remove entries that are unique but just leaves a single entry for a duplicate.

I have this so far but it is not good!

var ref;
      for(var i in movies) {
        ref = movies[i].title;
        if(this.titles.indexOf(ref) == -1) {
            movies.splice(i, 1);
        } else {
            this.titles.push(ref);  
        }
      }

where 'movies' is the first array in this question and this.titles is simply an empty array.

benhowdle89
  • 36,900
  • 69
  • 202
  • 331
  • As others are posting solutions with returning newly built arrays, I think the problem is that you're directly editing the array in the middle of iterating it, which could cause unwanted results. – Ian Oct 04 '12 at 19:33
  • If `movies` is an array, you shouldn't use a `for…in`-loop – Bergi Oct 04 '12 at 19:35
  • Possible duplicate: http://stackoverflow.com/questions/840781/easiest-way-to-find-duplicate-values-in-a-javascript-array – Ricardo Alvaro Lohmann Oct 04 '12 at 19:39

1 Answers1

0

Following code will create new Array with desired result: jsfiddle

    var arr = [
    {
        title: 'anchorman'
    },
    {
        title: 'happy gilmore'
    },
    {
        title: 'anchorman'
    }
];

var temp = {}, newArr = [];
for(var k =0;k< arr.length; k++){
    if(temp[arr[k].title]){
        newArr.push(arr[k]);
    }

temp[arr[k].title] = true;
}
arr = newArr;
//console.log(newArr);​
Anoop
  • 23,044
  • 10
  • 62
  • 76