0

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

4
  • this means that you don't have an undefined object at arr[k] and not an array Commented Oct 20, 2013 at 16:30
  • Are you sure you defined arr in the same code? It should work. BTW in your current code if your array is empty you will receive undefined Commented Oct 20, 2013 at 16:31
  • 1
    Works fine for me: fiddle. You sure your array is valid? Commented Oct 20, 2013 at 16:31
  • Are you 100% sure that your array has 10 rows? Commented Oct 20, 2013 at 16:35

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.