He estado tratando de averiguar por qué mi código no funciona.
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));Está usando return dentro de una función de devolución de llamada que no está en la función principal (twoSum()), por lo que la función towSum tiene solo un return [] , para evitar que pueda usar for loop en lugar del ejemplo twoSum1() , pero si insista en usar el método .forEach , según esta respuesta, puede usar otra función de retroceso para recibir el retorno como en el twoSum2()
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); });