Search code examples
javascriptarrayslodash

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.


Solution

  • 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>