Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

179
Views
Multiplying the values of elements inside an array by 2

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]
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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;
} 
about 4 years ago · Juan Pablo Isaza Report

0

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]

So to sum it up:

  1. If we're dealing with an array, map() each value to * 2
  2. Otherwise, just * 2 the value
  3. 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]

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!