Javascript SumOfTwo

I have a function getPairs which gets array and sum as a param and returns all possible pairs. But I have a problem with their position in the array and deleting it in some different input param

function getPairs (arr, sum) {
if (!arr.length) return []

        const result = []
        const numObject = {}

        for (let i = 0; i < arr.length; i++) {
            numObject[arr[i]] = i;
        }

        for (let i = 0; i < arr.length; i++) {
            const diff = sum - arr[i];

            if (numObject[diff] && numObject[diff] !== i) {
                result.push([diff, arr[i]])
                arr.splice(arr.indexOf(diff), 1)
                arr.splice(i, 1)
            }
        }
        

        return result
    }

    console.log(getPairs([], 0))
    console.log(getPairs([22, 3, 5, 0, 2, 2], 5))
    console.log(getPairs([-5, 33, 2, 2, 3, 5, 0, 10, 3], 5))
    console.log(getPairs([5, 5, 5, 0, 0, 0, 5], 5))
    console.log(getPairs([3, 3, 6, 0], 6))

    input: ([22, 3, 5, 0, 2, 2], 5)
    resutls must be: [[3, 2], [5, 0]]
    i get:           [[2, 3], [3, 2]]
    
    input: ([-5, 33, 2, 2, 3, 5, 0, 10, 3], 5)
    resutls must be: [[-5, 10], [2, 3], [2, 3], [5, 0]]
    i get:           [[10, -5], [3, 2], [0, 5]]

    input: ([5, 5, 5, 0, 0, 0, 5], 5)
    resutls must be: [[5, 0], [5, 0], [5, 0]]
    i get:           [[0, 5], [0, 5], [0, 5]]
 
    input: ([3, 3, 6, 0], 6)
    resutls must be: [[3, 3], [6, 0]]
    i get:   [[3, 3], [6, 0]]

Thanks!

1 thought on “Javascript SumOfTwo”

Leave a Comment