JavaScript - 'Normalize' array indexes

I am looking for a method to 'Normalize' array indexes in Javascript. I have a large array ( _spm ) containing values with numeric indexes like ( _spm[201023] ).

( For You, to understand: Re-indexing the array starting from zero. )

I would need a method to make all the records have a more human-friendly index ( and may also be sorted ).

I mean:

function normalize( arrayWithMessedUpIndexes ){ return reIndexedAndOrderedArray }

A possible input is the array _spm considering that:

 _spm[201023] = "s";
 _spm[376615] = "m";

A possible output of the method I am looking for ( using the input array above ):

 _spm[0] = "s"
 _spm[1] = "m"

Upvotes: 2

Views: 1733

Answers (2)

Moritz Roessler
Moritz Roessler

Reputation: 8631

You could use Array.prototype.filter

var arr = [];
arr [42] = "foo";
arr [1337] = "bar";

arr.filter (function () {return true}); //["foo", "bar"]

Now, how does this work?. Let's take a look at ES5 §15.4.4.20, which describes the process.

  • ... some initialization steps
  • 9. Repeat, while k < len
    • a. Let Pk be ToString(k).
    • b. Let kPresent be the result of calling the [[HasProperty]] internal method of O with argument Pk.
    • c. If kPresent is true, then
      • do the magic

Since the first initialized index of our example array is 42, for every n < 42, calling n in arr or arr.hasOwnProperty (n) evaluates to false.

Given that, the condition, described in step 9c, is not met, hence, the index is skipped.

Note that [].filter is ES5 and may not be compatible with older browsers.

Upvotes: 2

shyam
shyam

Reputation: 9368

Array indexes are always sorted so, all you need to do is remove the undesirable elements

_spm = _spm.filter(function(v) { return v != undefined });

Upvotes: 1

Related Questions