Answers for "Js how to return the sum of two numbers in an array"

14

sum of all numbers in an array javascript

const arrSum = arr => arr.reduce((a,b) => a + b, 0)
Posted by: Guest on March-23-2020
1

two sum javascript

var twoSum = function(nums, target) {
    //hash table
    var hash = {};

    for(let i=0; i<=nums.length; i++){
      //current number
        var currentNumber = nums[i];
        //difference in the target and current number
        var requiredNumber = target - currentNumber;
        // find the difference number from hashTable
        const index2 = hash[requiredNumber];

        // if number found, return index 
        // it will return undefined if not found
        if(index2 != undefined) {
            return [index2, i]
        } else {
           // if not number found, we add the number into the hashTable
            hash[currentNumber] = i;

        }
    }
};
Posted by: Guest on September-13-2020

Code answers related to "Js how to return the sum of two numbers in an array"

Code answers related to "Javascript"

Browse Popular Code Answers by Language