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?
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);
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] );
You can just do
var lastElement = myArray.map(_.last);
var lastElement = myArray.map((x) => {
return _.last(x);
});
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 );
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)
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);
Perhaps loop through them with a for loop.
lastElement = [];
for (var i = 0 ; i < myArray.length ; i++) {
lastElement.push(_.last(myArray[i]));
}