Nono.MA

Add a list of numbers in TypeScript

DECEMBER 21, 2021

Say you have a long list of numbers and you want to add them together, or maybe you wish to multiply them or do some other series of operations, to all of them. You can use a reducer, and here's a sample of how to define a reducer as a simply add-two function to add an entire list of numbers.

const numbers = [20, 30, 50];
const reducer = (previousValue, currentValue) => {
  return previousValue + currentValue;
}
const result = numbers.reduce(reducer); // 100

You could easily parse a plain-text list as well.

const text = '1.75 Milk\n0.70 Bread\n2.56 Yogurt';
const numbers = text.split('\n').map(s => parseFloat(s.split(' ')[0]));
const reducer = (previousValue, currentValue) => {
  return previousValue + currentValue;
}
const result = numbers.reduce(reducer); // 5.01

CodeTypescript