获取数组每个子数组的最后一个元素 [英] Get the last element of each sub-array of an array
本文介绍了获取数组每个子数组的最后一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道对于一个数组,它可以使用下划线的last
函数,因此在该数组的情况下为:
I know that for an array it can be used last
function of underscore, so in the case of this array it would be:
myArray = [32, 1, 8, 31];
lastElement = _.last(myArray);
问题是当存在这样的矩阵时:
The problem is when there is a matrix like this:
myArray = [[1, 3, 5], [55, 66, 77], [0, 1, 2]];
所需的结果是
lastElement = [5, 77, 2];
有什么建议吗?
推荐答案
You could simply use Array.from
:
var myArray = [[1, 3, 5], [55, 66, 77], [0, 1, 2]];
var res = Array.from(myArray, x => x[x.length - 1]);
console.log(res);
此处尚未回答的另一种可能性是 Array#reduce
:
Another possibility not already answered here would be Array#reduce
:
var myArray = [[1, 3, 5], [55, 66, 77], [0, 1, 2]];
var res = myArray.reduce((acc, curr) => acc.concat(curr[curr.length - 1]),[]);
console.log(res);
这篇关于获取数组每个子数组的最后一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文