Search code examples
javascriptarrayssortingindices

Can you close empty gaps between array indices in JavaScript?


I have an algorithm where some array will be given a new index, but the new index is not sequential. For the sake of time, just assume the new index is given to the array at random. Let's say I have this array:

const arr = [];
arr[5] = 'a'
arr[2] = 'b'
arr[9] = 'c'
arr[0] = 'd'

If I console.log this array to the output window, I get this:

['d', empty, 'b', empty × 2, 'a', empty × 3, 'c']

I'm wondering if it's possible to close/remove those empty gaps between values so the array entries are sorted by their actual index, so I can get this output:

['d', 'b', 'a', 'c']

Is there a short and easy way to do this?


Solution

  • You can just use Array.prototype.filter and filter out undefined values. You can take a shortcut by coercing them into boolean using the !! operator:

    arr.filter(x => !!x);
    

    This check is loose/dirty because anything falsy will be coerced to false, e.g. the numeric 0. If you really want to be strict and only filter out undefined, then you need a stricter predicate:

    array.filter(x => typeof x !== 'undefined');
    

    const arr = [];
    arr[5] = 'a';
    arr[2] = 'b';
    arr[9] = 'c';
    arr[0] = 'd';
    
    console.log(arr);
    console.log(arr.filter(x => !!x));
    console.log(arr.filter(x => typeof x !== 'undefined'));