Given an array of integers arr and a target sum target, find all pairs of distinct integers that add up to the target sum. Return an array of arrays containing these pairs sorted in ascending order. If there are no such pairs, return an empty array.
I have tried this, but it doesn’t work
function findPairs(arr, target) {
let arr1 = []
for (let i = 0; i <= arr.length - 1; i++) {
for (let j = i + 1; j < arr.length - 1; j++) {
if (arr[i] + arr[j] === target) {
arr1.unshift(arr[i], arr[j])
}
}
}
return new Array(arr1)
}
console.log(findPairs([3, 7, 8, 4, 5, 9], 12)) // [[3,9],[4,8],[5,7]]
console.log(findPairs([1, 2, 3, 4], 8)) // []
2
Answers
Here is a corrected version of your code:
You can also use
Array#reduce
andArray#sort
methods as follows:Following commented solution might help the OP getting (re)started with the OP’s own approach.
Since the implementation is based on mutating/emptying an array entirely, it firstly creates a shallow copy of the array which was passed to it.
It then stepwise empties the array until no to be processed item is left. With each iteration a
currentValue
getsshift
ed from the array. A flag which indicates whether a match was found is set to its initialfalse
value, and the array’s current length gets assigned to an index variable.The now following nested iteration counts the index down whilst accessing the next possibly matching value from the array’s current state, until either the array iteration was completed or a matching value was found. As for the latter case one does create the array of the matching pair which then gets
push
ed to the result array. One also needs to update the current array bysplice
ing the matching value from it (thus further emptying the array). Finally one needs to flag/indicate the matching pair in order to exit early from the innerwhile
iteration.