0

For example: [5, 4, 1] = 0 If it is easy question, I'm so sorry, but I'm new in JavaScript! Thanks from all answers

3
  • 5
    [5,4,1].reduce((a,b)=>a-b) ? Commented Jul 3, 2021 at 10:34
  • 1
    Does this answer your question? How to find the sum of an array of numbers Commented Jul 3, 2021 at 10:46
  • Since you mentioned in a comment that this is for a calculator, remember that this is going to be dependent on order (5 - 4 - 1) != (4 - 5 - 1) you might want to consider adding signed numbers (5 + -4 + -1) == (-4 + 5 + -1) or look into established conventions eg Reverse Polish notation Commented Jul 3, 2021 at 11:12

3 Answers 3

2

Use Array.prototype.reduce to reduce and Array to a single output:

const numbers = [5, 4, 1];
const sub = numbers.reduce((acc, num) => acc - num);
console.log(sub) // 0

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

1 Comment

I used that and yes, it works! Thank u for help <3
1

Using a for loop and if else:

const numbers =  [5,4,1] ;
let ans = 0; //Initialize ans with some value
if(numbers.length > 0) ans = numbers[0]; //If array has length >0, use the first value. This will let you handle single length arrays
for(let i = 1; i < numbers.length;i++){
  ans -= numbers[i]; //subtract for every other element
}
console.log(ans);

2 Comments

Um, for which case?
I used a Roko C. Buljan's answer, but thanks. I want to use it in my calculator
-1

You can take a look on Array.reduce function on mozilla docs.

const subtractNumbersFromArray = (arr) => {
  return arr.reduce((acc, currentValue) => acc - currentValue);
};

const result = subtractNumbersFromArray([5, 4, 1]) // 0
const result = subtractNumbersFromArray([10, 3, 2]) // 5

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.