Skip to content

Instantly share code, notes, and snippets.

@mnicole
Created October 18, 2017 04:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mnicole/2cb3686e101d7827273eb7479ff7cc05 to your computer and use it in GitHub Desktop.
Save mnicole/2cb3686e101d7827273eb7479ff7cc05 to your computer and use it in GitHub Desktop.
function to check for the position of 2 numbers that equal a certain sum
/**
* Function to check for the position of 2 numbers that equal a certain sum. Only one pair per array.
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
const twoSum = function(nums, target) {
let checked = {},
found;
nums.forEach((n, index) => {
if (found) return;
const complement = target - n;
if (checked[complement]) {
found = [checked[complement].position, index];
}
else {
checked[n] = { position: index };
}
})
return found;
};
const nums = [ 1, 3, 2, 9, 4, 8];
const target = 6;
const findPosition = twoSum(nums, target);
console.log(findPosition);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment