删除重复的数组项

时间:2016-03-21 14:37:37

标签: javascript jquery arrays

var arr = ["Chandelier", "Big Girls Cry", "Burn the Pages", "Eye of the Needle", "Hostage", "Straight for the Knife", "Fair Game", "Elastic Heart", "Free the Animal", "Fire Meet Gasoline", "Cellophane", "Dressed In Black", "Chandelier", "Elastic Heart", "Chandelier", "Chandelier", "Elastic Heart", "Elastic Heart", "Big Girls Cry", "Big Girls Cry"];

 $.each(arr, function(i,obj){
console.log(obj);
});

如何确保我的阵列是唯一的?

1 个答案:

答案 0 :(得分:1)

使用Array#filter()和临时对象。



var arr = ["Chandelier", "Big Girls Cry", "Burn the Pages", "Eye of the Needle", "Hostage", "Straight for the Knife", "Fair Game", "Elastic Heart", "Free the Animal", "Fire Meet Gasoline", "Cellophane", "Dressed In Black", "Chandelier", "Elastic Heart", "Chandelier", "Chandelier", "Elastic Heart", "Elastic Heart", "Big Girls Cry", "Big Girls Cry"],
    unique = arr.filter(function (a) {
        if (!this[a]) {
            this[a] = true;
            return true;
        }
    }, {});    
    
document.write('<pre>' + JSON.stringify(unique, 0, 4) + '</pre>');
&#13;
&#13;
&#13;