【问题标题】:What is the best way to find elements from an array in another array in js?在js中从另一个数组中的数组中查找元素的最佳方法是什么?
【发布时间】:2020-03-09 09:04:30
【问题描述】:

我有一个函数 buildList,参数中有一个数字数组。 我还有 11 个元素是数字,我想知道这些元素是否存在于数组中,如果一个元素不存在,我将其推送到另一个数组中。

其实是这样的:

public static buildList(numbers[]) {
const newArray= [];
    if (numbers.find(element => element === ELEMENT_ONE) === undefined ) {
      newArray.push(ELEMENT_ONE);
    }
    if (numbers.find(element => element === ELEMENT_TWO) === undefined ) {
      newArray.push(ELEMENT_TWO);
    }
    ....
}

我目前的直觉是用 11 个元素创建一个新数组并为每个元素做一个,但我不太确定性能会更好...... 有没有办法改进这段代码?因为我对 11 个元素做同样的事情

【问题讨论】:

    标签: javascript arrays performance


    【解决方案1】:

    function buildList(numbers) {
      let newArray = [];
      elevenElements = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
    
      // Use this logic to filter elements.
      newArray = elevenElements.filter(d => numbers.some(y => y === d))
      return newArray;
    }
    
    const result=buildList([1, 8, 9]);
    console.log(result)

    【讨论】:

      【解决方案2】:
          public static buildList(numbers[]) {
            const newArray = [];
            elevenElements = [1,2,3,4,5,6,7,8,9,10,11]
      
      // Use this logic to filter elements.
            newArray = elevenElements.filter(d => !numbers.includes(d))
          }
      

      【讨论】:

      • 只打印一个错误:SyntaxError: unexpected token: 'static'。 FF在这里。
      • @ceving 我刚刚写了用户请求的逻辑。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多