Adnan Baliwala
Adnan Baliwala

Reputation: 463

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?

Upvotes: 9

Views: 24959

Answers (4)

hallodom
hallodom

Reputation: 6549

Perhaps "underscore.js" will be useful here.

The _.compact() function returns a copy of the array with no undefined.

See: http://underscorejs.org/#compact

Upvotes: 3

M_R_K
M_R_K

Reputation: 6350

Easy,

var filterd_array = my_array.filter(Boolean);

Upvotes: 4

Dag Sondre Hansen
Dag Sondre Hansen

Reputation: 2499

This is easily done natively using Array.filter:

resetArr = orgArr.filter(function(){return true;});

Upvotes: 40

danmcardle
danmcardle

Reputation: 2109

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

Upvotes: 4

Related Questions