首页 > 解决方案 > 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"]

标签: javascript

解决方案


一种优化可能是使用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)

推荐阅读