Languages
[Edit]
EN

JavaScript - subtract array of numbers

0 points
Created by:
Dollie-Rutledge
806

In this article, we would like to show you how to subtract array of numbers using JavaScript.

Quick solution:

// ONLINE-RUNNER:browser;

const numbers = [10, 1, 2];
const sum = (accumulator, number) => accumulator - number;

console.log(numbers.reduce(sum));  // 7   (10 - 1 - 2 = 7)

 

Alternative solution

In this section, we present an alternative solution for older JavaScript versions.

// ONLINE-RUNNER:browser;

function subtract(accumulator, number) {
    return accumulator - number;
}

var numbers = [10, 1, 2];
var result = numbers.reduce(subtract);

console.log(result);  // 7   (10 - 1 - 2 = 7)

See also

  1. JavaScript - sum array of numbers

References

  1. Array.prototype.reduce() - JavaScript | MDN

Alternative titles

  1. JavaScript - find difference of array of numbers
  2. JavaScript - subtract array of numbers with reduce()
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join