gpt4 book ai didi

javascript - 检查数组的更多元素是否具有相同的 key 值,是否删除了一个?

转载 作者:行者123 更新时间:2023-12-01 04:01:05 25 4
gpt4 key购买 nike

所以我已经尝试了我所知道的一切。使用 map 和过滤器、原型(prototype)。没用。 .

[{"color":"black","type":"bmw"},{"color":"gray","type":"golf"}, {"color":"red","type":"bmw"}, {"color":"black","type":"mercedes"}] 

所以我想要实现的是,当我使用javascript执行ajax时,检查两个或多个对象是否具有相同的类型值,例如,如果有两个或多个宝马,则删除其他对象并推送一个宝马类型的物体。希望我说得足够清楚。提前致谢

最佳答案

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);

关于javascript - 检查数组的更多元素是否具有相同的 key 值,是否删除了一个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42182926/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com