I have a for
loop which returns an array.
Return:
1st loop:
arr[0]
arr[1]
arr[2]
arr[3]
Here the length I get is 4
(Not a problem).
Return:
2nd loop
arr[4]
arr[5]
arr[6]
arr[7]
arr[8]
Here the length I get is 9
.
What I want here is the actual count of the indexes i.e I need it to be 5
. How can I do this. And is there a way that when I enter each loop every time it starts from 0
so that I get proper length in all the loops?
A. length = 0; This is the only code that correctly empties the contents of a given JavaScript array.
Array indexing starts at zero in C; you cannot change that. If you've specific requirements/design scenarios that makes sense to start indexes at one, declare the array to be of length n + 1, and just don't use the zeroth position. Save this answer.
You can remove the element at any index by using the splice method. If you have an array named arr it can be used in this way to remove an element at any index: arr. splice(n, 1) , with n being the index of the element to remove. The splice method can accept many arguments.
This is easily done natively using Array.filter:
resetArr = orgArr.filter(function(){return true;});
You could just copy all the elements from the array into a new array whose indices start at zero.
E.g.
function startFromZero(arr) {
var newArr = [];
var count = 0;
for (var i in arr) {
newArr[count++] = arr[i];
}
return newArr;
}
// messed up array
x = [];
x[3] = 'a';
x[4] = 'b';
x[5] = 'c';
// everything is reordered starting at zero
x = startFromZero(x);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With