Skip to content

Instantly share code, notes, and snippets.

@garyb1
Created November 30, 2020 08:02
Show Gist options
  • Save garyb1/d88a7d394d0ad9e2f32d3426f50549cb to your computer and use it in GitHub Desktop.
Save garyb1/d88a7d394d0ad9e2f32d3426f50549cb to your computer and use it in GitHub Desktop.
arrayDiff interview question from the Cassidy Williams (cassidoo) newsletter
//Given an array of integers and a target value
//return the number of pairs of array elements
//that have a difference equal to the target value
//arrayDiff([1, 2, 3, 4], 1);
//Result = 3.
// 2 =1 = 1, 3 -2 = 1, 4 -3 = 1;
function arrayDiff(arr, target) {
return arr.reduce((accumulator, currentValue, currentIndex) => {
if (currentIndex === arr.length - 1) return accumulator;
const diff = arr[currentIndex + 1] - currentValue;
return diff === target ? accumulator + 1 : accumulator;
}, 0)
}
arrayDiff([1, 2, 3, 4], 1); // 3
arrayDiff([2, 5, 8, 11], 3); // 3
arrayDiff([2, 5, 11, 14], 6); // 1
arrayDiff([], 2); // 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment