【问题标题】:Comparing arrays to get the list of values比较数组以获取值列表
【发布时间】:2020-12-28 10:52:58
【问题描述】:

我有一个第一个数组的列表

const a = [{id:1, value:'apple'}, {id:2, value: 'ball'},{id:3, value: 'cat'}]

我还有另一个 id 数组

const ids = [1,2]

现在,我需要从a 获取数组值列表,它的 id 列在 ids 数组中。预期结果:

const b =  [{id:1, value:'apple'}, {id:2, value: 'ball'}]

【问题讨论】:

    标签: javascript arrays ecmascript-6 lodash


    【解决方案1】:

    您可以从 id 数组中创建一个 Set 并将 Array#filterSet#has 一起使用(在 O(1) 时间运行)以提高性能。

    const a = [{id:1, value:'apple'}, {id:2, value: 'ball'},{id:3, value: 'cat'}]
    const ids = [1,2]
    const idSet = new Set(ids);
    const res = a.filter(({id})=>idSet.has(id));
    console.log(res);

    【讨论】:

      【解决方案2】:

      如果我在这里的理解正确,您希望从a 获取ids 集合中具有匹配id 的每条记录的value 参数?

      let results = a.filter(node=>ids.indexOf(node.id) !== -1);
      

      分解Array.prototype.filter 命令:

      a.filter 在功能上告诉编译器迭代a 集合(如for 循环);虽然从它的回调返回一个真实值时返回的唯一记录返回它(在node=>位之后应用的函数)。

      node 是分配给迭代中正在检查的活动索引的临时变量。

      ids.indexOf(...) 它请求集合中node.id 的数字索引。如果node.id 在集合中不存在,则indexOf 返回-1

      因此,综上所述:“循环遍历a,并针对其中包含的每个对象,针对ids 测试每个对象,并返回truefalse,具体取决于是否找到(一些值 OTHER 不是 -1) 或不是 (-1)。Array.filter 将自动仅显示结果为 true 的那些。

      【讨论】:

        【解决方案3】:

        你可以使用Array.prototype.filter:

        a.filter(({ id }) => ids.includes(id));
        

        const a = [{id:1, value:'apple'}, {id:2, value: 'ball'}];
        
        const ids = [1,2];
        
        const result = a.filter(({ id }) => ids.includes(id));
        
        console.log(result);

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-02-10
          • 1970-01-01
          • 1970-01-01
          • 2021-07-15
          • 2018-10-30
          相关资源
          最近更新 更多