使用 Lodash 获取数组内每个数组的第一个元素

7
这是一个仅使用JS的答案在这里。但是,仅仅因为我想更熟练地使用Lodash,所以我寻找 Lodash 的解决方案。
假设我有一个看起来像这样的数组: [[a, b, c], [d, e, f], [h, i, j]] 我想将每个数组的第一个元素作为自己的数组: [a, d, h] 请问使用 Lodash 最高效的方法是什么?谢谢。

3
将数组arr中每个元素的第一个值提取出来,赋值给变量result。实现方法是使用map方法和箭头函数,箭头函数的参数为a,返回a的第一个值a[0]。具体代码如下:let result = arr.map(a => a[0]) - ibrahim mahrir
2
在这种情况下不需要使用 lodash。 - amd
Lodash版本:let result = _.map(arr, a => a[0]); - ibrahim mahrir
5个回答

10

你可以使用_.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>


为什么他们要有一个获取数组第一个元素的方法? - slider
也许用于表头? - Nina Scholz
Head非常有用!它来自函数式语言,如lisp、scheme...你通常可以添加一个参数来告诉它你想要多少个第一个元素,非常基本但有用的过滤功能。此外,在R、Python中与数据结构(如数据框)一起使用。 - godot

3

如果你想使用lodash:

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

1
使用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,那么可以使用ES6ES5

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] }))

实际上,性能和实际代码几乎相同。


0
你还可以使用_.matchesProperty迭代器简写,许多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>


0

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)

这应该可以做到,但我不明白为什么你想在纯JavaScript中已经存在几乎相同的过滤函数时要使用lodash。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接