[英]Use Lodash to get first element of each array inside array
This question as a JS-only answer here . 这个问题作为一个JS-回答只有在这里 。 But simply because I'd like to become more proficient with Lodash, I'm looking for the Lodash solution. 但仅仅因为我想更加熟练地使用Lodash,我正在寻找Lodash解决方案。
Let's say I have an array that looks like: 假设我有一个看起来像的数组:
[[a, b, c], [d, e, f], [h, i, j]]
I'd like to get the first element of each array as its own array: 我想将每个数组的第一个元素作为自己的数组:
[a, d, h]
What is the most efficient way to do this with Lodash? 使用Lodash最有效的方法是什么? Thanks. 谢谢。
You could use _.map
with _.head
for the first element. 您可以将_.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>
Or just the key. 或者只是关键。
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>
If you want to use lodash: 如果你想使用lodash:
const _ = require('lodash')
const arr1 = [[a, b, c], [d, e, f], [h, i, j]]
arr2 = _.map(arr1, e => e[0])
https://lodash.com/docs/#filter https://lodash.com/docs/#filter
Use the docs, look for some each function. 使用文档,查找每个函数。
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)
This should do it, but I don't understand why you wanna use lodash when pretty much the same filter function exists in vanilla javascript. 这应该这样做,但我不明白为什么你想使用lodash,当香草javascript中存在几乎相同的过滤功能。
With lodash you can do this with _.first
, _.head
( _.first
is just an alias of _.head
) and direct path
while mapping
through the array: 随着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>
If you however have to use lodash
just for this then simply use either ES6 or ES5 : 但是,如果您必须使用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] }))
The performance and actual code is the same practically. 性能和实际代码实际上是相同的。
You can also use the _.matchesProperty
iteratee shorthand, which many lodash methods support. 您还可以使用_.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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.