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 Answers
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
1 Comment
Czarek Czareski
I used that and yes, it works! Thank u for help <3
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
Tushar Shahi
Um, for which case?
Czarek Czareski
I used a Roko C. Buljan's answer, but thanks. I want to use it in my calculator
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
[5,4,1].reduce((a,b)=>a-b)?(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