Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace all undefined values in an array with "-"?

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.

like image 678
Jaybruh Avatar asked May 13 '26 06:05

Jaybruh


2 Answers

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);
like image 126
Nina Scholz Avatar answered May 15 '26 21:05

Nina Scholz


You can use Array.map

var array = [1, 2, undefined, undefined, 7, undefined];
var newArray = array.map(x => x !== undefined ? x : "-");
console.log(newArray);
like image 24
Vladu Ionut Avatar answered May 15 '26 20:05

Vladu Ionut



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!