从 javascript 中的嵌套数组中获取 uniq 值的更快方法



这是一个检查,以确保我没有使我的程序过于复杂。我有一些代码可以找到子节点,按 tagName 过滤,然后获取它们的数据属性。这一切都很顺利。

但是,数据属性中存在重复项,因此必须按唯一值对其进行筛选。因此,我再次映射并推送到一个新列表,只要它们还没有在那里。

我看到的问题是这会在循环内创建一个嵌套循环,可能会减慢速度。有没有更快的方法来做到这一点?

请注意,我不是在征求您对这里最好的意见。我只想知道是否有更快的选择。

var productList = Array.from(document.querySelectorAll(".grid li"))
var _productList = productList.map(function (item) {
var a = Array.from(item.children)
var b = a.filter(item => item.tagName == "SPAN").map(item => item.dataset.colors)
let newList = []
b.map(i => !newList.includes(i) && newList.push(i))
return newList
})
console.log(_productList)
// 0: (2) ["yellow", "white"]
// 1: ["gray"]
// 2: ["white"]
// 3: ["white"]
// 4: ["light_brown"]
// 5: (2) ["beige", "white"]
// 6: ["blue"]
// 7: (2) ["burgandy", "White"]

一种优化可能是使用Sets,而不是创建自定义逻辑来过滤重复项。

通过这样做,您可以将过滤控制权交给浏览器的 JS 引擎,并且它可能会做得更快(或至少不会更慢(:

var productList = Array.from(document.querySelectorAll(".grid li"))
var _productList = productList.map(item => [
...new Set(
Array
.from(item.children)
.filter(item => item.tagName == "SPAN")
.map(item => item.dataset.colors)
)
])
console.log(_productList)

这是一个让javascript为你完成工作的解决方案。

let values = ["1", "2", "2", "3", "3", "3"];
let distinctValues = {};
for (let value of values) {
// Javascript's objects are actually maps, which inherently have unique keys.
// Therefore we can place all values into the object and let javascript handle the de-duplication.
distinctValues[value] = null;
}
for (let distinctValue in distinctValues) {
// This only prints distinct values (1, 2, 3)
console.log(distinctValue);
}

最新更新