0

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));
pilchard
  • 12,414
  • 5
  • 11
  • 23
  • 1
    What are you trying to do? What is your expected output? – Andy May 11 '22 at 23:26
  • 1
    You can't return early out of a `forEach`, you'll need to use a `for...of` or just a `for` loop, from the [docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach#description): *'Note: There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool.'*. Also `forEach` always returns `undefined` so assigning it to variable is pointless. – pilchard May 11 '22 at 23:45

1 Answers1

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);
});
ismail bilal
  • 80
  • 1
  • 3