Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Given an array of numbers and a target, return an array of unique indices that sum to the target
const sumToTarget = (arr, target) => {
if (!Array.isArray(arr) || arr.length < 2) { return []; } // Check for bad input
const results = [];
const hash = {};
for (var i = 0; i < arr.length; i += 1) {
const current = arr[i];
if (hash[current] === undefined) {
hash[target - current] = i;
} else {
results.push([hash[current], i]);
}
}
return results;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment