gpt4 book ai didi

javascript - 如果数组项有重复的 id,则删除它

转载 作者:行者123 更新时间:2023-12-02 21:44:57 24 4
gpt4 key购买 nike

我有一个包含以下值的数组:

expandedComponents: {
components: [
{componentName: "hero", componentId: "hero-5856bvC6"},
{componentName: "features", componentId: "features-iAnIKgJN"},
{componentName: "features", componentId: "features-ncf3WpTA"},
{componentName: "features", componentId: "features-iAnIKgJN"},
{componentName: "features", componentId: "features-ncf3WpTA"},
{componentName: "footer", componentId: "footer-cUSAiiVd"}
]
}

我想过滤掉任何具有重复 componentId 的数组项。

this.removeDuplicatesBy(x => x.componentId, this.expandedComponents['components']);

removeDuplicatesBy(keyFn, array) {
var set = new Set();
return array.filter(function(x) {
var key = keyFn(x), isNew = !set.has(key);
if (isNew) set.add(key);
return isNew;
});
}

但是似乎什么也没发生,重复的 features 字段仍然存在。我该如何解决这个问题?

最佳答案

One liner - Using Set

components = [{componentName:"hero",componentId:"hero-5856bvC6"},{componentName:"features",componentId:"features-iAnIKgJN"},{componentName:"features",componentId:"features-ncf3WpTA"},{componentName:"features",componentId:"features-iAnIKgJN"},{componentName:"features",componentId:"features-ncf3WpTA"},{componentName:"footer",componentId:"footer-cUSAiiVd"}];
console.log(components.filter((set => f => !set.has(f.componentId) && set.add(f.componentId))(new Set)))

Taken From

旧版浏览器不支持 JavaScript 集 Read HereHere ,但您可以使用 polyfill对于旧浏览器的支持

关于javascript - 如果数组项有重复的 id,则删除它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60278909/

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