3

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.

halfer
  • 19,824
  • 17
  • 99
  • 186
Jaybruh
  • 333
  • 5
  • 14

9 Answers9

4

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);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
3

You can use Array.map

var array = [1, 2, undefined, undefined, 7, undefined];
var newArray = array.map(x => x !== undefined ? x : "-");
console.log(newArray);
Vladu Ionut
  • 8,075
  • 1
  • 19
  • 30
2

You can map the values and return - if undefined.

let array = [1, 2, undefined, undefined, 7, undefined]

let result = array.map(o => o !== undefined ? o : '-');

console.log(result);
Eddie
  • 26,593
  • 6
  • 36
  • 58
2

Use Array.map()

var array = [1, 2, undefined, undefined, 7, undefined];
console.log(array);

var newArray = array.map(function(v) {
  return undefined === v ? '-' : v;
});

console.log(newArray);
1
var newArray = array.map(function(val) {
    if (typeof val === 'undefined') {
        return '-';
    }
    return val;
});
Mark
  • 3,224
  • 2
  • 22
  • 30
1
 function SampleArray() {
            var Array = [];
            var array = [1, 2, undefined, undefined, 7, undefined];
            for (var i = 0; array.length > i; i++) {
                var Value;
                if (array[i] == undefined) {
                    Value = '-';
                } else {
                    Value = array[i];
                }

                Array.push(Value);
            }
        }
kalai
  • 187
  • 11
0

Try using this -

array.forEach(function(part,index,Arr){ if(!Arr[index])Arr[index]='-'})
0

You can use functional programming map function:

 let array = [1, 2, undefined, undefined, 7, undefined];

 let array2 = array.map(e => e === undefined ?  e='-' :  e);
Marek Urbanowicz
  • 12,659
  • 16
  • 62
  • 87
Leigh Cheri
  • 126
  • 10
0

Try:

while((index = array.indexOf(undefined)) > -1){array[index] = "-";}

"-"

this will search for the index of the value you are searching for, and replace it with "-"