What is your hint or solution suggestion?
function pairwise(arr, arg) {
const usedIndices = [] // Array to store the pairs of indices
for (let i = 0; i < arr.length; i++){ // Iterating through arr
let index = arr.indexOf( // Gets index of value in the array
arr.find( // Gets the first value of the array that satisfacts the callback function
n => n && // Value can't be null
!usedIndices.flat().includes(n) && // Value can't be in usedIndices array
arr[i] + n === arg // Value + arr[i] === arg must be true
)
)
if (index >= 0 && // Index must be a positive number
!usedIndices.flat().includes(i) && // Index can't be in usedIndices array
index !== i) { // Index === i must be false
arr[i] = null // Set arr[i] and arr[index] to null to avoid them from being detected by arr.indexOf()
arr[index] = null
usedIndices.push([i, index]) // Puts pair in usedIndices array
}
}
if (usedIndices.length === 0) return 0 // If nothing of that worked, return 0
return usedIndices.flat().reduce((a, b) => a + b) // Otherwise, add up all the values inside the 2D array and return the result
}
console.log(pairwise([7, 9, 11, 13, 15], 20)); // Logs 6
Challenge: Pairwise
Link to the challenge: