Can anyone tell me why when I call the function, I’m getting undefined. I can access the result inside of the function but not outside.
function twoSum(nums, target) {
console.log(nums); // keep track of user input.
console.log(target); // keep track of target.
let arrayOfIndices = [];
// loop through array and perform addition operation
for (let i = 0; i < nums.length; i++) {
for (let j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] === target) {
arrayOfIndices.push([i, j]);
}
}
}
if (arrayOfIndices.length === 0) {
console.log("No two sum exists");
} else {
console.log(arrayOfIndices);
}
let result = arrayOfIndices;
console.log(result);
}
// Test case
console.log(twoSum([3, 4, 5], 7));
2
Answers
You need to add
return result
to the last line of your function. It’s not returning anything.This looks like a LeetCode problem (Two Sum). You over-complicating this because your algorithm is taking O(n^2) time. It also does not short-circuit (early return), so you are computing all the sums for every number in the array.
As others have already mentioned, you will need to return the array of indices in your function. You did not do that. I do not see
return arrayOfIndices
nor do I seereturn result
anywhere in that function.Just store the remainder in a map where the needed value (compliment) is a value you have yet to encounter. Once you have the compliment, return it’s index; along with the stored remainder’s index.