Let say I have an array created by Array.fill()
and I want to replace the undefined value with an empty string. These are some of the methods I use:
- With
.map()
let data = Array(5).fill(-2, 0, 1).fill(0,2,3).fill(2,4,5);
console.log(data);
data = data.map(d => d ? d : '');
console.log(data);
- With
.forEach()
let data = Array(5).fill(-2, 0, 1).fill(0,2,3).fill(2,4,5);
console.log(data);
data.forEach((_,i) => {
data[i] = data[i] ? data[i] : '';
});
console.log(data);
- With
for ... in
.
let data = Array(5).fill(-2, 0, 1).fill(0,2,3).fill(2,4,5);
console.log(data);
for(let i in data) {
data[i] = data[i] ? data[i] : '';
}
console.log(data);
My expectation is to print something like this: [-2, "", 0, "", 2]
. All three methods give same result but are not correct. Why did it happen? Did I miss something?
Note: The purpose of this question is to replace undefined values with empty strings, not just to know why the below methods didn’t work. So this question shouldn’t be duplicated
2
Answers
When you create an array with
Array(5)
, it is a sparse array. This means all elements are<empty>
. When you usemap/forEach/for in
, these functions only iterate over non-empty elements. This is why empty strings are not being filled in.To fill it with empty strings first, do:
To fill in the empty elements afterwards, do:
Note that StackOverflow’s console function prints
undefined
instead of<empty>
.This code should work. I tried out the for-Each and it seems like to skip all indexes that are undefined. That makes sense since i is in your case also undefined.
This version iterates through every index, since i is always incremented after every iteration. Then it’s easy to check if the current index has the value of undefined.