I have an array like:
var array = [1, 2, undefined, undefined, 7, undefined]
and need to replace all undefined values with "-". The result should be:
var resultArray = [1, 2, "-", "-", 7, "-"]
I think there is a simple solution, but I couldn't find one.
You could check for undefined and take '-', otherwise the value and use Array#map for getting a new array.
var array = [1, 2, undefined, undefined, 7, undefined],
result = array.map(v => v === undefined ? '-' : v);
console.log(result);
For a sparse array, you need to iterate all indices and check the values.
var array = [1, 2, , , 7, ,],
result = Array.from(array, v => v === undefined ? '-' : v);
console.log(result);
You can use Array.map
var array = [1, 2, undefined, undefined, 7, undefined];
var newArray = array.map(x => x !== undefined ? x : "-");
console.log(newArray);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With