I am trying to make a function that can take either an array or a value, and double it. I tried looking for a way to grab each element in an array, and then multiply it by 2, but I am not getting the needed result when I run the code.
I feel like I am missing something simple here, but searching through stackoverflow and google hasn't helped me resolve this.
Thanks in advance for an advice/help!
function double(value) {
if (Array.isArray(value)) {
value = value.map(function(element) {
return element * 2;
});
}
return value * 2;
}
// What the results should be, if it works:
double(2); // 4
double([1, 2, 3]); // [2, 4, 6]
CodePudding user response:
You just have to return the value.
function double(value) {
if (Array.isArray(value)) {
return value.map(function(element) {
return element * 2;
});
}
return value * 2;
}
CodePudding user response:
return value * 2;
will produce NaN
if value
is an array.
You only want to do the *
if value
isn't an array like so:
function double(value) {
if (Array.isArray(value)) {
value = value.map(function(element) {
return element * 2;
});
} else {
value *= 2;
}
return value;
}
console.log(double(2)); // 4
console.log(double([1, 2, 3])); // [2, 4, 6]
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
So to sum it up:
- If we're dealing with an array,
map()
each value to* 2
- Otherwise, just
* 2
thevalue
- Return
value
I've decided to alter value
to show the issue, the only difference with @Munleashed answer is that he's returning the value right away, we could simplify this even more using an arrow function like so:
if (Array.isArray(value)) {
return value.map((v) => v * 2);
} else {
return value * 2;
}
Then, why not go further by using a ternary operator:
function double(value) {
return (Array.isArray(value)) ? value.map((v) => v * 2) : (value * 2);
}
console.log(double(2)); // 4
console.log(double([1, 2, 3])); // [2, 4, 6]
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>