Reputation: 9
given this array ['1', 23, null, 46.5, '34e2', , false, 'true', , 40], how can i divide the numeric elements in it by 10, but also keeping the non numeric elements in it, without modifying those values. what i did so far is this:
var divide = numbers.map(function(x){
if(typeof x === 'number' && isFinite(x)){
return x / 10;
}
});
console.log(divide); // [undefined, 2.3, undefined, 4.65, undefined, 6: undefined, 7: undefined, 9: 4]
Upvotes: 0
Views: 73
Reputation: 480
You are returning the the numerical value but you are not handling the case if x
isn't a number just add return x
after the if condition and it would work perfectly :)
var divide = numbers.map(function(x){
if(typeof x === 'number' && isFinite(x)){
return x / 10;
}
return x;
});
Upvotes: 2
Reputation: 253446
The problem is that Array.prototype.map()
will return a value from the anonymous function performed on each iteration over the Array, and without a specific value to be returned it will – as will any JavaScript function – simply return undefined
if a specific value isn't provided to be returned (as you found out); so the key is to return the current value if that value doesn't match the conditions of the if
assessment.
var numbers = ['1', 23, null, 46.5, '34e2', , false, 'true', , 40],
divide = numbers.map(function(x) {
if ('string' === typeof x && isFinite(x)) {
return x / 10;
} else {
return x;
}
});
console.log(divide);
Incidentally, as you're not using this
anywhere, and if ES6` is an option for you, and your users, you could also use Arrow functions:
var numbers = ['1', 23, null, 46.5, '34e2', , false, 'true', , 40],
divide = numbers.map(x => 'string' === typeof x && isFinite(x) ? x/10 : x);
console.log(divide);
References:
Upvotes: 2
Reputation: 42490
Your mapping function has to return a value for each of the elements, not only the numeric ones:
var divide = numbers.map(function(x){
if(typeof x === 'number' && isFinite(x)){
return x / 10;
} else return x;
});
Upvotes: 3