Home > front end >  How to filter an array of arrays and just return part of each inner array?
How to filter an array of arrays and just return part of each inner array?

Time:10-19

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

CodePudding user response:

.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]);

CodePudding user response:

When you call map on an array, it executes that callback on every element

within it, returning a new array with all of the values that the callback

returned.

Filter does exactly what it sounds like: It takes an array and filters out unwanted elements.

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

console.log(myArray.map(item=>item[1]))
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related