Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to replace missing/undefined values in an array?

I need to process some arrays that contains undefined values, like the following:

[ 1, 1, 1, 1, 1, , 1, 1 ]
[ 1, , 1, , , 1, 1 ]
[ 1, , , , , 1, 1 ]

What I need to achieve is not a removal of the undefined values, but I need to replace them with zeros.

I tried to use underscore.js to achieve this; without success.

The following is my solution attempt:

binarymap = _.map(binarymap, function(curr){
    // let's replace all undefined with 0s
    if(_.isUndefined(curr)) {
        return 0;
    }
    return curr;
});

Unfortunately, it does not work. underscore.js's function _.map totally ignores undefined values.

Any ideas? Elegant solutions?

like image 777
fstab Avatar asked Sep 12 '26 21:09

fstab


2 Answers

The actual problem here is the missing array elements,

Array elements may be elided at the beginning, middle or end of the element list. Whenever a comma in the element list is not preceded by an AssignmentExpression (i.e., a comma at the beginning or after another comma), the missing array element contributes to the length of the Array and increases the index of subsequent elements. Elided array elements are not defined. If an element is elided at the end of an array, that element does not contribute to the length of the Array.

And Array.prototype.map skips all the missing array elements,

callbackfn is called only for elements of the array which actually exist; it is not called for missing elements of the array.

So, in order to make the Array elements to be considered by the map function, the simplest way I could think of is to tweak your approach a little bit, like this

var arr = [ 1, , , , , 1, 1 ];
console.log(_.map(Array.apply(null, arr), function (currentItem) {
    return _.isUndefined(currentItem) ? 0 : currentItem;
}));
# [ 1, 0, 0, 0, 0, 1, 1 ]

Here, Array.apply (which is actually Function.prototype.apply) does the important thing, converting the missing elements to undefined.

console.log(Array.apply(null, arr));
# [ 1, undefined, undefined, undefined, undefined, 1, 1 ]
like image 169
thefourtheye Avatar answered Sep 14 '26 11:09

thefourtheye


Is this what you mean..?

var arr = [ 1, , , , , 1, 1 ];
for( var i = 0; i < arr.length; i++ ) {
 if( typeof(arr[i])==="undefined" ) {
  arr[i] = 9;
 }
}
console.log( arr );

// yields [1, 9, 9, 9, 9, 1, 1] 
like image 29
EricG Avatar answered Sep 14 '26 11:09

EricG



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!