-1
var cars = [
    { year: 2007, model: "Ford F-150" },
    { year: 2011, model: "Toyota Camry" },
    { year: 2007, model: "Ford F-150" },
    { year: 2007, model: "Ford F-150" },
    { year: 2005, model: "Dodge RAM" }
    { year: 2005, model: "Dodge RAM" };
];

How Remove duplicate from this array list

blex
  • 24,941
  • 5
  • 39
  • 72

1 Answers1

2

It is easy to filter duplicates base on indexOf condition, this works for simple items. In your case you can't use it because two similar objects in array are not identical so indexOf will not help.

For this situation it is convenient to make use of Array.prototype.reduce:

var cars = [
    { year: 2007, model: "Ford F-150" },
    { year: 2011, model: "Toyota Camry" },
    { year: 2007, model: "Ford F-150" },
    { year: 2007, model: "Ford F-150" },
    { year: 2005, model: "Dodge RAM" },
    { year: 2005, model: "Dodge RAM" }
]; 

cars = cars.reduce(function(prev, curr) {
    var inArray = prev.some(function(car) {
        return car.model === curr.model && car.year === curr.year;
    });
    if (!inArray) {
        prev.push(curr);
    }
    return prev;
}, []);

alert(JSON.stringify( cars, null, 4) )
dfsq
  • 191,768
  • 25
  • 236
  • 258