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

190
Vistas
Two Sums JS (forEach)

I've been trying to figure out why my code is not working.

const twoSum = function (arr, target) {
  const newMap = new Map();
  const newArr = arr.forEach(function (num, i, arr) {
    if (newMap.has(target - num)) return [newMap.get(target - num), i];
    else newMap.set(num, i);
    console.log(newMap);
  });
  return [];
};

console.log(twoSum([3, 1, 3, 4, 5, 1, 2, 3], 9));

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You are using return inside a callback function not in the main function (twoSum()), so the towSum function has only one return [] , to avoid that you can use for loop instead as in the twoSum1() example, but if you insist to use .forEach method, Based on this answer you can use another collback function to receive the return like in the twoSum2() exapmle

const twoSum1 = function (nums, target) {
  const newMap = new Map();
  for (let i = 0; i < nums.length; i++) {
    const num = nums[i];
    if (newMap.has(target - num)) {
      return [newMap.get(target - num), i];
    }
    newMap.set(num, i);
  }
};

console.log("from the first method: ");
console.log(twoSum1([3, 1, 3, 4, 5, 1, 2, 3], 9));

const twoSum2 = function (arr, target, fn) {
  const newMap = new Map();
  const newArr = arr.forEach(function (num, i) {
    if (newMap.has(target - num)) fn([newMap.get(target - num), i]);
    else newMap.set(num, i);
  });
  return newArr;
};

twoSum2([3, 1, 3, 4, 5, 1, 2, 3], 9, (result) => {
  console.log("from the second method: ");
  console.log(result);
});

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