保持数组中最后一个元素具有相同的属性

Keeping the last element in an array with the same property

本文关键字:属性 元素 数组 最后一个      更新时间:2023-09-26

假设我有这样一个数组:

bucket.bucketList =[];
bucket.addItem = function(item) {
  bucket.bucketList.push(item);
}

函数在每次鼠标滚动时将一个名为foo this的对象压入数组:

一些 foo's也有一个性质,foo.name = "something";

问题是,什么是最好的方法来删除所有重复基于他们的名称属性名称,同时保持最近的一个推入?

我已经在我的项目中使用jQuery,所以如果jQuery有一个比香草JS更优雅的方式来做这件事,我会更乐意使用它。

此代码删除所有重复的名称,保留数组中的最后一个。

您可以向后遍历数组并删除具有您已经看到的名称的任何项,使用对象来跟踪您已经看到的名称。通过向后遍历,您保留了最后一个,并且当您从数组中删除当前条目时无需进行任何数组索引更正:

var dict = {}, item;
for (var i = bucket.bucketList.length - 1; i >= 0 ; i--) {
    item = bucket.bucketList[i];
    if (item.name) {
        // if already in the dict, remove this array entry
        if (dict[item.name] === true) {
            bucket.bucketList.splice(i, 1);
        } else {
            // add it to the dict
            dict[item.name] = true;
        }
    }
}