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
Asked
Active
Viewed 719 times
0
-
5`[5,4,1].reduce((a,b)=>a-b)` ? – Jaromanda X Jul 03 '21 at 10:34
-
1Does this answer your question? [How to find the sum of an array of numbers](https://stackoverflow.com/questions/1230233/how-to-find-the-sum-of-an-array-of-numbers) – pilchard Jul 03 '21 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](https://en.wikipedia.org/wiki/Reverse_Polish_notation) – pilchard Jul 03 '21 at 11:12
3 Answers
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

Roko C. Buljan
- 196,159
- 39
- 305
- 313
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);

Tushar Shahi
- 16,452
- 1
- 18
- 39
-
-
I used a Roko C. Buljan's answer, but thanks. I want to use it in my calculator – Czarek Czareski Jul 03 '21 at 10:56
-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

Furkan
- 14
- 3