Search code examples
javascriptarraysreplaceundefinedarray-map

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.


Solution

  • 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);