How to filter an array of arrays and just return part of each inner array?

Viewed 227

I have the following array of arrays:

const myArray = [ ['1', 'first'], ['2', 'second'], ['3', 'third'], ['4', 'fourth'] ]

I want to return an array like:

[ 'first', 'second', 'third', 'fourth' ]

I'm trying the following filter:

const res = myArray.filter( elm => elm[1] )

but it doesn't return the desired filter, just return the same...

1 Answers

.filter() is used to create a subset of an array containing elements that pass a certain requirements test.

.map() is used create a new array consisting of the results of passing the elements through a function.

The following should work as you intend:

const res = myArray.map(elm => elm[1]);
Related