Get the last element of each sub-array of an array

2019-03-07 08:51发布

问题:

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

and the wanted result is

lastElement = [5, 77, 2];

Any suggestions?

回答1:

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

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



回答2:

Use map and slice (Won't mutate the original array)

[[1, 3, 5], [55, 66, 77], [0, 1, 2]].map( s => s.slice(-1)[0] );


回答3:

You can just do

var lastElement = myArray.map(_.last);


回答4:

var lastElement = myArray.map((x) => {
   return _.last(x);
});


回答5:

Or you can also use ES6 map

let myArray = [[1, 3, 5], [55, 66, 77], [0, 1, 2]]; 
let result = myArray.map(v => v[ v.length - 1] );

console.log(result );



回答6:

Check this out. Iterate over the array using map and extract last element.

No need of any library.

let myArray = [[1, 3, 5], [55, 66, 77], [0, 1, 2]]; 
let output = [];

output = myArray.map(m => m[m.length - 1] )

console.log(output)



回答7:

You can use array.prototype.map to transorm each subarray to the last element in it. You can get those last elements with array.prototype.pop or arr[arr.length - 1] if you don't want to mutate myArray:

var myArray = [[1, 3, 5], [55, 66, 77], [0, 1, 2]]; 
var lastElements = myArray.map(arr => arr.pop());
console.log(lastElements);



回答8:

Perhaps loop through them with a for loop.

lastElement = [];

for (var i = 0 ; i < myArray.length ; i++) {
    lastElement.push(_.last(myArray[i]));
}


回答9:

Use Following Code:-

var myArray = [[1, 3, 5], [55, 66, 77], [0, 1, 2]];
lastElement = _.map(myArray, _.last);
console.log(lastElement)
// **Result is lastElement = [5, 77, 2];**
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>