简体   繁体   中英

How to get last number of an array of arrays?

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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