Koka
Koka

Reputation: 23

How to sum the array elements by reduce method js

why my cod is not working i mean can i even sum with reduce method?

function sum() {
    let numbers = [] ;
    let result ;
    while(true) {
        let input = prompt("Enter a number or press 'S' to submit") ;
        if(input === "s" || input === null) {
            break;
        }
        numbers.push(Number(numbers)) ;
    }
    **let submaition = numbers.reduce(myfun); 
    function myfun(a , b) {
        result = parseInt(a) + parseInt (b) ;
        return result ;
    }**
}

Upvotes: 1

Views: 73

Answers (4)

Nithish
Nithish

Reputation: 5999

There are few issues in the implementation,

  • It should be numbers.push(Number(input)) rather than numbers.push(Number(numbers))
  • And if a string is entered then the result will be NaN

I have addressed these issues in the below code.

function sum() {
    let numbers = [] ;
    let result ;
    while(true) {
        let input = prompt("Enter a number or press 'S' to submit") ;
        if(input === "s" || input === null) {
            break;
        }
        if(isNaN(Number(input))) input = 0;
        numbers.push(Number(input));
    }
    console.log(numbers);
    let submaition = numbers.reduce(myfun, 0); 
    function myfun(a , b) {
        result = a + b ;
        return result;
    }

    return submaition
}

console.log(sum())


Hope this helps.

Upvotes: 1

ROOT
ROOT

Reputation: 11622

You should pass initial value to the reduce function also there is an error in numbers.push(Number(numbers)) ; it should be numbers.push(Number(input)) ; here is a working snippet:

function sum() {
  let numbers = [];
  let result;
  while (true) {
    let input = prompt("Enter a number or press 'S' to submit");
    if (input === "s" || input === null) {
      break;
    } else {
      numbers.push(Number(input));
    }
  }

  let submaition = numbers.reduce(myfun, 0);
  function myfun(a, b) {
    return parseInt(a)+ parseInt(b);
  }
  console.log(submaition);
}

sum();

Upvotes: 1

Benjamín Escobar
Benjamín Escobar

Reputation: 242

Your reduce function is o.k. The problem is that you are not pushing the correct value to the Numbers array. Instead of:

numbers.push(Number(numbers)) ;

Use this:

numbers.push(Number(input)) ;

I hope this helps you out.

Upvotes: 1

Nairi Areg Hatspanyan
Nairi Areg Hatspanyan

Reputation: 749

Yes

const euros = [29.76, 41.85, 46.5];

const sum = euros.reduce((total, amount) => total + amount); 

console.log(sum) // 118.11

Upvotes: 1

Related Questions