skip to Main Content

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:

  1. 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);
  1. 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);
  1. 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


  1. When you create an array with Array(5), it is a sparse array. This means all elements are <empty>. When you use map/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:

    let data = Array(5).fill('').fill(-2, 0, 1).fill(0,2,3).fill(2,4,5);
    console.log(data);

    To fill in the empty elements afterwards, do:

    let data = Array(5).fill(-2, 0, 1).fill(0,2,3).fill(2,4,5);
    console.log(data);
    data = Array.from(data, e => e??'');
    console.log(data);

    Note that StackOverflow’s console function prints undefined instead of <empty>.

    Login or Signup to reply.
  2. let data = Array(5).fill(-2, 0, 1).fill(0,2,3).fill(2,4,5);
    console.log(data);
    for (let i = 0; i<data.length;i++) {
        if (data[i] === undefined)
      data[i] = "";
    }
    console.log(data);
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search