Consider this / Please try this yourself in the chrome console.
data = [1,,2,,3]
now i want to replace the empty values with 0
data = [1,0,2,0,3]
I did:
data = data.map(e => {
if (e===undefined)
{
return 0;
}
else
{
return e;
}
});
But it is still returning the empty values as empty. what is right way to do this?
Consider this / Please try this yourself in the chrome console.
data = [1,,2,,3]
now i want to replace the empty values with 0
data = [1,0,2,0,3]
I did:
data = data.map(e => {
if (e===undefined)
{
return 0;
}
else
{
return e;
}
});
But it is still returning the empty values as empty. what is right way to do this?
Share Improve this question edited Dec 5, 2018 at 19:07 Shidersz 17.2k2 gold badges27 silver badges51 bronze badges asked Dec 5, 2018 at 18:48 KitKarsonKitKarson 5,70714 gold badges55 silver badges75 bronze badges 3-
e === null
should do the trick – full-stack Commented Dec 5, 2018 at 18:49 - No @goldie, it does not help – KitKarson Commented Dec 5, 2018 at 18:50
- Another option is to return 0 unless the value passes the if test. Check typeof 'number', for example – Brian Wagner Commented Dec 5, 2018 at 18:52
3 Answers
Reset to default 8The problem is that map
doesn't call the function for the missing elements of the array. From MDN:
callback
is invoked only for indexes of the array which have assigned values, includingundefined
. It is not called for missing elements of the array (that is, indexes that have never been set, which have been deleted or which have never been assigned a value).
The same is true of forEach
.
You need to loop through the array indexes rather than using one of the mapping functions.
for (let i = 0; i < data.length; i++) {
if (!(i in data)) {
data[i] = 0;
}
}
Note that using i in data
makes it only skip nonexistent entries. If you have an explicit undefined
it will be left, e.g.
[1, , undefined, 3, 4]
will bee
[1, 0, undefined, 3, 4]
If you want the explicit undefined
to be replaced, you can use i === undefined
instead.
Array.from()
is handy for this. It will use the length
to iterate over the array so it won't skip undefined values like map()
does. You can pass the value to its second parameter which is a function and return the value or
0:
let data = [1,,2,,3]
let new_array = Array.from(data, i=> i || 0)
console.log(new_array)
Trying looping over the length of the array and filling the gaps:
for(var i = 0; i < data.length; i++)
{
if(typeof(data[i]) === 'undefined')
{
data[i] = 0;
}
}