简体   繁体   English

如何过滤 arrays 的数组并只返回每个内部数组的一部分?

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

I have the following array of arrays:我有以下 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...但它没有返回所需的过滤器,只是返回相同的......

.filter() is used to create a subset of an array containing elements that pass a certain requirements test. .filter()用于创建包含通过特定需求测试的元素的数组的子集。

.map() is used create a new array consisting of the results of passing the elements through a function. .map()用于创建一个新数组,该数组由通过函数传递元素的结果组成。

The following should work as you intend:以下应该按您的意愿工作:

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

When you call map on an array, it executes that callback on every element当您在数组上调用 map 时,它会在每个元素上执行该回调

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. Filter 的作用与它听起来完全一样:它接受一个数组并过滤掉不需要的元素。

 const myArray = [ ['1', 'first'], ['2', 'second'], ['3', 'third'], ['4', 'fourth'] ] console.log(myArray.map(item=>item[1]))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM