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.
(*): Returns the first element(s) of array .
The first and last elements are accessed using an index and the first value is accessed using index 0 and the last element can be accessed through length property which has one more value than the highest array index. The array length property in JavaScript is used to set or return the number of elements in an array.
Note: In most programming languages, the first array index is 0 or 1, and indexes continue through the natural numbers. The upper bound of an array is generally language and possibly system specific.
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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With