I have pasted the same code below with comments explaining the code flow.
Hope this is clear, let me know if you have any doubts.
Cheers!
let twoSum = (array, sum) => {
let hashMap = {}, //Defining an object to keep track of the values that we come across as we iterate through the array
results = [] //The final result array
for (let i = 0; i < array.length; i++) { //For loop iterating through the array of numbers
// If condition checking if the hashMap has already seen a compliment of the current number.
//That is, if 10 is the required sum and 6 is the current number, then the compliment of 6 is 4.
//So checking if we have already come across 4 in the array.
//If we have, then we are adding it in the results array.
if (hashMap[array[i]]) {
results.push([hashMap[array[i]], array[i]])
} else {
//Flow has come to "else" since we have not come across the compliment of the current number,
//Hence we are adding this number to the map and continuing to the next number
//If required sum is 10, and the current number is 6. The hashMap Entry will be {4:6} (Complimentary number : Current number)
//Thus next time if we get "4", we will check if (hashMap[4]) exists.
//If it does, then that means we have already come across 6 in this array. Then the entry [6.4] will be added to the results array.
hashMap[sum - array[i]] = array[i];
}
}
return results;
}