简体   繁体   中英

Use Lodash to get first element of each array inside array

This question as a JS-only answer here . But simply because I'd like to become more proficient with Lodash, I'm looking for the Lodash solution.

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? Thanks.

You could use _.map with _.head for the first element.

 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:

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

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.

With lodash you can do this with _.first , _.head ( _.first is just an alias of _.head ) and direct path while mapping through the array:

 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 :

 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.

 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM