Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need to reset just the indexes of a Javascript array

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?

like image 286
Adnan Baliwala Avatar asked Jul 10 '12 13:07

Adnan Baliwala


People also ask

How do you flush an array in JavaScript?

A. length = 0; This is the only code that correctly empties the contents of a given JavaScript array.

Can we change array index?

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.

How do you remove an element from an array index?

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.


2 Answers

This is easily done natively using Array.filter:

resetArr = orgArr.filter(function(){return true;});
like image 164
Dag Sondre Hansen Avatar answered Nov 12 '22 11:11

Dag Sondre Hansen


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);
like image 22
danmcardle Avatar answered Nov 12 '22 11:11

danmcardle