Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Loop through sparse array and replace sparse values

I'm trying to loop through a sparse array and fill in sparse elements with a value.

['foo', 'bar', , , ,].map(el => el || 'default') // returns ["foo", "bar", undefined × 3]

How would I return ["foo", "bar", "default", "default", "default", "default"]

like image 307
Blexy Avatar asked Jan 07 '23 18:01

Blexy


1 Answers

Since .map (and also .forEach) will skip sparse values there's no option except to use a loop, but you should explicitly check for the absence of the missing keys

for (var i = 0, n = a.length; i < n; ++i) {
    if (!(i in a)) {       // explicit check for missing sparse value
        a[i] = "default";
    }
}
like image 166
Alnitak Avatar answered Jan 30 '23 05:01

Alnitak