Search code examples
javascriptecmascript-2016

Find Two numbers When added to give Target number


I wrote this code to find two numbers when added give a target number. I have already solved this exercise but I want to make with this way above in the if statement didn't return true and I don't know why.

function add(arr , target){
    let result = [];
    arr.map ( (item) => {
        const num1 = target - item;
        if (arr.includes(num1)) {
            return result.concat(num1 , item);
        }
        else {
            return "Unfortunaly there isnt answer";
        }
    });
}

add([3,4,5,6,10] , 16);

Solution

  • function add(arr , target){
        let result = [];
        for (let item of arr){
            const num1 = target - item;
            if (arr.includes(num1)) {
                return result.concat(num1 , item);
            }
        };
        return "Unfortunately there is no answer";
    }
    
    const result = add([3,4,5,6,10] , 16);
    
    // will print [10, 6]
    console.log(result)