Array Sum

Array Sum

Array Sum is when we sum all the numbers in the array ___

##For Example
[1,6,4,2,14] => true
[1,2,4,34,22] => false

##



function arraySum(arr){
  let tempArr = arr.sort((a,b) {
    return a - b;
    })
    let largest = tempArr.pop();
    let number = 0;
    tempArr.forEach(item => number +=item);
    return largest === number
}

function arraySum(arr) {

First we create a function called arraySum and pass an argument called arr.



let tempArr = arr.sort((a,b)=>{
return a - b;
})



We create tempArr and then fill the tempArr with the sorted array where we create arr.sort method where we create callback function with a and b as parameters. And we return a-b



let largest = tempArr.pop(); let number = 0; tempArr.forEach(item => number +=item)



We use the pop() method to pop the last item in the sorted array in our case tempArr.pop() and we use the variable largest to put the largest number in the variable largest. We also create a variable number = 0; And we use the tempArr.forEach(item => number +=item) for each item in the tempArr add it to the number variable.



return largest === number



At the end we return true if largest is equal to number or false if they are not equal



comments powered by Disqus