Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
119
rated 0 times [  125] [ 6]  / answers: 1 / hits: 7961  / 10 Years ago, fri, march 14, 2014, 12:00:00

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?


More From » arrays

 Answers
7

If you wanted to you could add the function as a mixin for use in an underscore chain. Improvised from here.



_.mixin({
dothis: function(obj, interceptor, context) {
return interceptor.call(context, obj);
}
});

function resetArray(arr) {
for (var i = 0, l = arr.length; i < l; i++) {
if (arr[i] === undefined) arr[i] = 0;
}
return arr;
}

var arr = [ 1, , , , , 1, 1 ];

_(arr)
.chain()
.dothis(resetArray)
.tap(console.log) // [1, 0, 0, 0, 0, 1, 1]


Fiddle



Edit: actually, there's a simpler way of doing that:



_.mixin({
resetArray: function (arr) {
for (var i = 0, l = arr.length; i < l; i++) {
if (arr[i] === undefined) arr[i] = 0;
}
return arr;
}
});

var arr = [1, , , , , 1, 1];

_(arr)
.chain()
.resetArray()
.tap(console.log)


Fiddle


[#46845] Thursday, March 13, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
joanneamiyaa

Total Points: 532
Total Questions: 127
Total Answers: 98

Location: Guam
Member since Tue, Nov 3, 2020
4 Years ago
;