Need to reset just the indexes of a Javascript array
Asked Answered
C

4

9

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?

Crinkly answered 10/7, 2012 at 13:1 Comment(2)
can you post the relevant code?Raynaraynah
You need to show us the loop you are using, the condition inside it and the initialisation of your array in the first place.Gabrielson
H
40

This is easily done natively using Array.filter:

resetArr = orgArr.filter(function(){return true;});
Hanny answered 14/12, 2013 at 18:28 Comment(4)
Worked perfect for me!Cinchonize
+1 clean solution. It works even using the same array: origArr = origArr.filter(...)Reproachful
Note that this will not work for IE <= 8. You may implement this suggested polyfill to solve that problem: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…Hanny
Bit shorter version : resetArr = orgArr.filter(Boolean);Varicose
V
4

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);
Virgate answered 10/7, 2012 at 13:13 Comment(2)
i love you crazedgremlin..you made my dayCrinkly
You're welcome! Just so you know, this is a bad solution to your problem -- you should probably choose a new data structure such as a linked list that will allow you to delete items without having to recreate the array each time. Also, you should choose an answer if you have found a solution to your problem!Virgate
V
4

Easy,

var filterd_array = my_array.filter(Boolean);
Varicose answered 8/3, 2019 at 14:38 Comment(0)
B
3

Perhaps "underscore.js" will be useful here.

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

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

Beccafico answered 16/4, 2013 at 19:18 Comment(1)
awesome lib ; applies to arrays and also avoid removal of non empty objects.Coleorhiza

© 2022 - 2024 — McMap. All rights reserved.