Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

180
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda