所以我尝试了所有我知道的东西。使用地图和过滤器,原型。没工作。
[{"color":"black","type":"bmw"},{"color":"gray","type":"golf"}, {"color":"red","type":"bmw"}, {"color":"black","type":"mercedes"}]
所以我想要实现的是,当我使用javascript执行ajax时,检查两个或更多对象是否具有相同的类型值,如果有两个或更多bmw-s,则删除其他对象并推送一个宝马类型的对象。希望我很清楚。 提前致谢
答案 0 :(得分:1)
function removeDuplicates(arr) {
var alreadyExist = {}; // hash object to keep track of elemnt that have already been encountered
var indexes = []; // array of indexes that will be removed
arr.forEach(function(o, i) { // for each object o in arr
if(alreadyExist[o.type]) // if the type of the object o at index i already exist
indexes.push(i); // mark its index i to be removed later
else // if not
alreadyExist[o.type] = true; // then mark the object as found so other ones will be removed
});
// for each index in the indexes array
for(var i = 0; i < indexes.length; i++)
arr.splice(indexes[i] - i, 1); // remove the object at that index ( - i because the array arr is continually changing. Its length decrease every time we remove an item)
}
var array = [{"color":"black","type":"bmw"},{"color":"gray","type":"golf"}, {"color":"red","type":"bmw"}, {"color":"red","type":"bmw"}, {"color":"red","type":"bmw"}, {"color":"black","type":"mercedes"}];
removeDuplicates(array);
console.log(array);
答案 1 :(得分:1)
不删除元素,创建过滤后的数组:
var yourArray = [{"color":"black","type":"bmw"},{"color":"gray","type":"golf"}, {"color":"red","type":"bmw"}, {"color":"black","type":"mercedes"}];
var cache = {},
filteredArray = yourArray.filter(({type}) => type in cache? false: (cache[type] = true));
console.log(filteredArray);
它具有非破坏性,性能更高,更简单,更短。
修改,即使没有现代功能:
var filteredArray = yourArray.filter(function(item){
return item.type in this? false: (this[item.type] = true);
}, {/* the cache-object */}); //abusing `this` to pass the cache object
答案 2 :(得分:0)
您可以使用对象跟踪数组中已存在的类型,然后只将那些不存在的数组推送到新数组中:
var vehicles = [{"color":"black","type":"bmw"},{"color":"gray","type":"golf"}, {"color":"red","type":"bmw"}, {"color":"black","type":"mercedes"}];
var uniques = [];
var types = {};
for (var i = 0; i < a.length; i++) {
if (!types[a[i].type]) { uniques.push(a[i]); }
types[a[i].type] = true;
}
//uniques = [{"color":"black","type":"bmw"},{"color":"gray","type":"golf"}, {"color":"black","type":"mercedes"}];