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, '-',
Solution 1:
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);
Solution 2:
You can use Array.map
var array = [1, 2, undefined, undefined, 7, undefined];
var newArray = array.map(x => x !== undefined ? x : "-");
console.log(newArray);
Solution 3:
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);
Solution 4:
var newArray = array.map(function(val) {
if (typeof val === 'undefined') {
return'-';
}
returnval;
});
Solution 5:
Try using this -
array.forEach(function(part,index,Arr){ if(!Arr[index])Arr[index]='-'})
Post a Comment for "How To Replace All Undefined Values In An Array With "-"?"