How to find the two indices of numbers in an array that sum to a specific target

Here is one way to find the two indices of numbers in an array that sum to a specific target:

twoSumTry in REPL
1
2
3
4
5
6
7
8
9
10
11
function twoSum(a, b) {
const obj = {};
for (let i = 0; i < nums.length; i++) {
const num = nums[i];
if (obj[target-num] !== undefined) {
return [obj[target-num], i];
}
obj[num] = i;
}
return [] // We can also throw an error here.
}