I have the following arrangement:
var a = ["1", "2", "0", "4"]
...and I want to convert it to:
[1, 2, null, 4]
So far I have managed to convert the array from string to number with this command:
var g = a.split(",").map(Number);
... and gives me this result:
[1, 2, 0, 4]
How can I convert the value zero in the array to null
?
You can achieve it using:
+var
to cast the value ofvar
a numbervar || null
for the case thatvar
is falsy assignnull
Namely:
demonstration:
If you are interested in modifying the array, not creating a new one. You can do it with
forEach
the following way.The key here is that inside the loop we modify each value
a
by its index by doinga[i] = +n || null
, leaving a single array as a result:From the result, I would make a map with a condition in which to see if the number is 0, and if so, I pass null.
According to the needs of your solution, a correct answer could be.
Let's remember that map can receive a callback which, in this case, is a function that is called on each element of the array. This function allows us to take the element and, according to certain conditionals, return a specific value by manipulating it. This is what allows us to check if the value is 0 or not. If it is a normal number, there we do call Number(value) to return the number. Otherwise, we return null.
You could use findIndex, it
findIndex()
returns the index of the first element of an array that matches the given test function. Otherwise it returns -1. once you find in index you do the replacement