2

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"
2
  • Can't you just loop through and push the entries to a new array? Or is there some mystery to this that you are leaving out? Commented Nov 18, 2013 at 14:27
  • Would make sense, but isn't there any faster way? Commented Nov 18, 2013 at 14:28

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

As far as I know this will not reindex the array's records, will it?
@StevenPalinkas Yes, it will, I added a little explanation. Looking for a nice Answer on SO that describes those implicit undefined. I'll add it when i found one
@StevenPalinkas didn't found a good one, added an explanation based on the ES5 specification
1

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

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

2 Comments

What a coincidence ^^. No need for the undefined check though, unless you want to filter explicit undefineds. As the others are implicit and won't get iterated over
@C5H8NNaO4 True. Never had to rely on that behavior before :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.