I am implementing a hash map for the Two Sum leetcode problem.
const testArrs = {
'first': [2,7,11,15],
'second': [3,2,4],
'third': [3,3]
}
function twoSum(nums, target) {
let mapped = nums.map((item) => target - item);
let returnedArr = mapped.filter((item) => {
if (nums.includes(item)) {
console.log(nums.indexOf(target-item))
return nums.indexOf(target - item)
}
})
console.log(returnedArr)
//TODO check if returnedArr size == 2.
}
twoSum(testArrs['first'], 9)
The first array mapped creates an array of hashes as "indexes" that are the difference of target from each element in the nums array. Then I apply a filter to the mapped array to see if 2 elements of the mapped array are contained in the nums array, returning the index of those elements.
When the indexes are filtered into the returnedArr it seems to return the first element of nums instead of two indexes. [2] instead of [0,1] The logging before the return shows it is correctly registering indexes 0 and 1 respectively.