Skip to content

Instantly share code, notes, and snippets.

@StevenXL
Created June 24, 2015 14:35
Show Gist options
  • Save StevenXL/5ee6c946ebd7ab2ce752 to your computer and use it in GitHub Desktop.
Save StevenXL/5ee6c946ebd7ab2ce752 to your computer and use it in GitHub Desktop.
FreeCodeCamp - Pairwise
function pairwise(arr, arg) {
// hold the indexes that add up to arg
var indexes = [];
// iterate over each element in the original array
arr.forEach(function (curVal, index, array) {
var outerIndex = index;
// compare to each element in the original array
array.forEach(function (val, indx, ar) {
var innerIndex = indx;
// if you are comparing the same index of the original array
// then don't take any action
if (outerIndex === innerIndex) {
// do nothing
}
// if the values adds up:
else if (curVal + val === arg) {
// pus the indexes of the values to the indexes array if that index is not already there
if (indexes.indexOf(outerIndex) === -1) {
indexes.push(outerIndex);
}
if (indexes.indexOf(innerIndex) === -1) {
indexes.push(innerIndex);
}
}
});
});
// sum up the values
return indexes.reduce(function(previousValue, currentValue) {
return previousValue + currentValue;
}, 0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment