【问题标题】:Use Lodash to get first element of each array inside array使用 Lodash 获取数组中每个数组的第一个元素
【发布时间】:2018-11-29 20:11:12
【问题描述】:

此问题仅作为 JS 答案here。但仅仅因为我想更加精通 Lodash,我正在寻找 Lodash 解决方案。

假设我有一个如下所示的数组:

[[a, b, c], [d, e, f], [h, i, j]]

我想将每个数组的第一个元素作为自己的数组:

[a, d, h]

使用 Lodash 最有效的方法是什么?谢谢。

【问题讨论】:

  • let result = arr.map(a => a[0])
  • 在这种情况下不需要 lodash
  • Lodash 版本:let result = _.map(arr, a => a[0]);

标签: javascript arrays lodash


【解决方案1】:

您可以使用_.map 和_.head 作为第一个元素。

var data = [['a', 'b', 'c'], ['d', 'e', 'f'], ['h', 'i', 'j']],
    result = _.map(data, _.head);

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

或者只是钥匙。

var data = [['a', 'b', 'c'], ['d', 'e', 'f'], ['h', 'i', 'j']],
    result = _.map(data, 0);

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

【讨论】:

  • 大声笑为什么他们有一个方法来获取数组的第一个元素?
  • 也许是表格的标题?
  • 头部很有用!它来自 lisp、scheme 等函数式语言……您通常可以添加一个参数来说明您想要多少个第一个元素,这是非常基本但有用的过滤。它也用于 R、Python 中,数据结构为 sushi 作为数据帧。
【解决方案2】:

如果你想使用 lodash:

const _ = require('lodash')
const arr1 = [[a, b, c], [d, e, f], [h, i, j]]
arr2 = _.map(arr1, e => e[0])

【讨论】:

    【解决方案3】:

    使用 lodash,您可以使用 _.first、_.head(_.first 只是 _.head 的别名)和直接 path 而 mapping 通过数组:

    const data = [['a', 'b', 'c'], ['d', 'e', 'f'], ['h', 'i', 'j']]
    
    console.log(_.map(data, _.first))
    console.log(_.map(data, _.head))
    console.log(_.map(data, 0)) // direct path
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

    如果您必须为此使用 lodash,那么只需使用 ES6 或 ES5:

    const data = [['a', 'b', 'c'], ['d', 'e', 'f'], ['h', 'i', 'j']]
    
    console.log(data.map(x => x[0]))
    console.log(data.map(function(x){ return x[0] }))

    性能和实际代码几乎是一样的。

    【讨论】:

      【解决方案4】:

      https://lodash.com/docs/#filter

      使用文档,查找每个函数。

      let arr = [[a, b, c], [d, e, f], [h, i, j]]
      let newArray = _.filter(arr, function(subArray){
         return subArray[0] // first element of each subArray
      })
      console.log(newArray)
      

      应该这样做,但我不明白为什么你要使用 lodash,而香草 javascript 中存在几乎相同的过滤器功能。

      【讨论】:

        【解决方案5】:

        您还可以使用_.matchesProperty iteratee 速记,许多 lodash 方法都支持该速记。

        const data = [['a', 'b', 'c'], ['d', 'e', 'f'], ['h', 'i', 'j']];
        
        const result = _.map(data, '[0]');
        
        console.log(result);
        <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

        【讨论】:

          猜你喜欢
          • 2021-10-05
          • 1970-01-01
          • 2020-07-21
          • 2010-12-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-05-26
          相关资源
          最近更新 更多