如何从列表数组中删除Duplicate

时间:2015-07-04 11:09:26

标签: javascript jquery

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" };
];

如何从此数组列表中删除重复

1 个答案:

答案 0 :(得分:2)

根据indexOf条件轻松过滤重复项,这适用于简单项目。在您的情况下,您无法使用它,因为数组中的两个相似对象不相同,因此indexOf无效。

对于这种情况,可以方便地使用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) )