Reputation: 5154
I have an array. It consists of 10 arrays.
var arr = [[], [], [], [], [], [], [], [], [], []];
Every of this 10 arrays has different number of numbers. I want to get last numbers in that 10 arrays.
I have tried to do such a way:
var lastNums = [];
var i = 0;
var j = 0;
for (var k = 0; k < 10; k++) {
i = arr[k].length - 1; //This code gets number of the last number
lastNums[j] = arr[k][i];
j++;
}
But it doesn't seems to work. In Chrome Console I get:
TypeError: Cannot read property 'length' of undefined
Upvotes: 0
Views: 115
Reputation: 14689
If you don't have an error defining the array arr, you can do this:
lastNumbers = arr.map(function(k){
return k[k.length - 1];
})
now the lastNumbers array will hold the last number of each array in arr. The good thing with using the built in array map function is that you don't need to care about the size of your array. The above solution works for any length of array.
Upvotes: 2
Reputation: 2168
var arr = [[1,2,3], [4,5,6,7], [8,5,6], [1,6,4,2], [8,6,3,2], [4,5,7,8], [5,4,2,2,1], [5,6,7], [4], [8,8]];
var lastNums = [];
for(var i=0;i<arr.length;i++){
if(arr[i].length > 0){
lastNums.push(arr[i][arr[i].length-1]);
}
}
alert(lastNums);
Upvotes: 0