javascript - Faster way to get uniq values from nested array in javascript
问题描述
This is a check to make sure I am not complicating my programs more than they need to be. I have some code that finds children nodes, filtered by tagName, and then grabs their data-attributes. This is all smooth.
However there are duplicates in the data-attributes, and so they must be filtered by unique values. Therefor I map through again and push to a newList as long as they are not already in there.
The problem i see is this creates a nested loop inside of a loop, probably slowing this down. Is there a faster way to do this?
Please note i am not asking for your opinion on what is best here. I just want to know if there are options that would be faster.
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"]
解决方案
一种优化可能是使用Set
s 而不是创建自定义逻辑来过滤重复项。
通过这样做,您可以将过滤控制权交给浏览器的 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)
推荐阅读
- kubernetes - 在 yaml 文件中将连接字符串作为环境变量传递
- python-3.x - Python Salesforce API 身份验证
- css - 如何将多行列表中的最后一项居中,保持每行的高度和相同的间隙?
- java - 如何从头开始创建对象的 LinkedList(不使用 java 的 API)
- oracle - Oracle 动态调用游标
- tableau-api - 在仪表板上使用不相关的表创建从到工作表的总计
- docker - Gitlab - 使用“docker in docker”服务的作业导致“无法连接到 Docker 守护程序”
- java - Payara/Glassfish JAX-RS 多部分
- r - 如何从 input$.. 或 output$.. 获取路径并将其用于 list.files 然后复制/剪切文件
- ruby-on-rails - “[attribute]_changed”是如何变化的?使用 CarrierWave mount_uploader :[attribute]?