Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 654
MegaMatt Avatar asked Nov 29 '18 20:11

MegaMatt


People also ask

How do you get the first element of an array Lodash?

(*): Returns the first element(s) of array .

How do you access the first element of an 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.

What is the first index of 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.


2 Answers

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>
like image 73
Nina Scholz Avatar answered Oct 30 '22 23:10

Nina Scholz


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])
like image 28
godot Avatar answered Oct 31 '22 00:10

godot