【问题标题】:Lodash, find indexes of all matching elementsLodash,查找所有匹配元素的索引
【发布时间】:2017-05-18 09:59:46
【问题描述】:

使用lodash,如何获取所有匹配元素的索引数组? 例如:

Animals = [{Name: 'Dog', Id: 0},
          {Name: 'Cat', Id: 1},
          {Name: 'Mouse', Id: 2},
          {Name: 'Horse', Id: 3},
          {Name: 'Pig', Id: 3}]

然后我想用Id == 3查找所有元素的索引。

预期输出:

Indexes = [3,4];

【问题讨论】:

  • 听起来你需要某种循环。
  • 没有别的办法了吗?
  • _.each 是一个循环。

标签: typescript lodash


【解决方案1】:

这是一个简短的解决方案:

Indexes = _.keys(_.pickBy(Animals, {Id: 3}))

输出:

Indexes = ["3", "4"]

使用pickBy 选择元素,使用keys 获取索引。

pickBy 用于对象

_.pickBy(object, [predicate=_.identity])

创建一个由对象属性谓词返回truthy 组成的对象。谓词使用两个参数调用:(value, key)。

https://lodash.com/docs/4.17.10#pickBy

但是当在数组上使用时,它会返回一个类似

的对象
{
  3: {Name: "Horse", Id: 3},
  4: {Name: "Pig", Id: 3}
}

在这个对象上使用_.keys来获取字符串数组中的所有键

["3", "4"]

如果要获取数字数组,请使用_.map

_.map(_.keys(_.pickBy(Animals, {Id:3})), Number)

你会得到

[3, 4]

【讨论】:

  • 虽然此代码可能会回答问题,但提供有关它如何和/或为什么解决问题的额外上下文将提高​​答案的长期价值。
【解决方案2】:

另一种解决方案:

_.filter(_.range(animals.length), (i) => animals[i].id === 3);

id === 3 是上面问题中定义的过滤条件。

【讨论】:

    【解决方案3】:

    我认为最直接的方法是将其分解:1) 我们需要找出哪些对象的 ID 为 3,2) 摆脱其他所有内容,以及 3) 获取我们感兴趣的索引在。

    _.chain(animals)
        .map((animal, i)=> [i, animal.id === 3])
        .filter(pair=> pair[1])
        .map(pair=> pair[0])
        .value();
    

    【讨论】:

      【解决方案4】:
      _.filter(
        _.map(Animals, (animal, index) => animal.id === 3 ? index : -1), 
        (index) => index >= 0
      )
      

      编辑:animal.id === 3 是上述问题中定义的过滤条件。

      【讨论】:

      • 请在答案中添加一些上下文,说明您的代码行正在做什么。如果这是一个好的解决方案,这将对未来的访问者有所帮助。
      【解决方案5】:

      这就是 reduce 的用途:

      _.reduce(Animals, function(result, value, key) {
                if(value.Id == 3) result.push(key);
       }, {});
      

      【讨论】:

        【解决方案6】:

        您可以将@AliYang 答案与链一起使用,对我来说,它看起来更具可读性:

        const findAllIndexes = <T>(array: Array<T>, predicate?: ValueKeyIteratee<T>) => {
          return chain(array)
            .pickBy(predicate)
            .keys()
            .map(Number)
            .value();
        }
        

        这个实现是带TS的,ValueKeyIteratee类型来自lodash,可以看到是lodash的pickBy使用的

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-05-31
          • 1970-01-01
          • 2021-05-19
          • 2015-12-20
          • 2017-05-06
          • 2015-05-07
          • 2018-12-29
          • 2015-05-13
          相关资源
          最近更新 更多