1

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 ;
    }**
}
1
  • Welcome to Stackoverflow. When asking a question it is better to show what research you have done into your problem and post detail of errors you are getting. Please read How do I ask a good question? and edit your question accordingly. Commented Jun 18, 2020 at 16:38

4 Answers 4

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

Yes

const euros = [29.76, 41.85, 46.5];

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

console.log(sum) // 118.11

Comments

1

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();

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.