Sum only the numbers in a mixed array in JavaScript
Beginner · 3 min read
Real data is messy. A spreadsheet export, a form or an API response can hand you a list like [1, 'two', 3, null, 4.5], where only some values are numbers. Adding them all up blindly gives nonsense. You need to pick out the real numbers first.
In this tutorial you will write sumStrict(values), which adds only real, usable numbers, and sumLenient(values), which also accepts text such as '6'. Along the way you will meet two values that call themselves numbers but break every sum: NaN and Infinity. You need to know what an array and a function are.
What JavaScript calls a number
typeof tells you the type of a value as a string:
console.log(typeof 3); // number
console.log(typeof 'two'); // string
console.log(typeof null); // object
console.log(typeof NaN); // number
console.log(typeof Infinity); // number
The last two are the surprise. NaN means "Not a Number", and it is what you get from math that fails, such as 0 / 0. Infinity is what you get from 1 / 0. Both have the type number, and both ruin a total:
console.log(1 + NaN); // NaN
console.log(1 + Infinity); // Infinity
Number.isFinite(value) is true only for ordinary numbers you can count with. It says false for NaN, Infinity and anything that isn't a number at all.
filter and reduce
filter keeps the items that pass a test. reduce walks a list and builds up one value, here a running total that starts at 0:
console.log([1, 2, 3].filter((v) => v > 1)); // [ 2, 3 ]
console.log([1, 2, 3].reduce((n, v) => n + v, 0)); // 6
Here is the exercise. Try it yourself first if you like, or read on and we will build it together.
45 Sum only the numbers in a mixed list
easyAdd up the numeric values in a list that also contains other things. Be careful about what counts as a number.
Stuck? Three hints, smallest first
- 1.
typeof v === 'number'is the check, but it also acceptsNaNandInfinity. - 2.
Number.isFinite(v)accepts only real, usable numbers. - 3. Should the string
'5'count? Decide and say so, rather than letting coercion decide for you.
Step 1: the tempting version
Keep anything whose type is number, then add:
const mixed = [1, 'two', 3, null, 4.5, undefined, NaN, Infinity, true, '6'];
const sumTypeof = (values) =>
values.filter((v) => typeof v === 'number').reduce((n, v) => n + v, 0);
console.log(sumTypeof(mixed)); // NaN
One NaN in the list turned the whole total into NaN, and nothing warned you. That is the trap.
Step 2: keep only finite numbers
Add Number.isFinite to the test. Now NaN and Infinity are left out:
const mixed = [1, 'two', 3, null, 4.5, undefined, NaN, Infinity, true, '6'];
const sumStrict = (values) =>
values.filter((v) => typeof v === 'number' && Number.isFinite(v))
.reduce((n, v) => n + v, 0);
console.log(sumStrict(mixed)); // 8.5
console.log(sumStrict([])); // 0
console.log(sumStrict(['a', null])); // 0
The total is 1 + 3 + 4.5. An empty list, or a list with no numbers, sums to 0 because the total starts at 0.
Number.isFinite alone would already give the same result, since it says false for anything that isn't a number. The typeof check is kept to make the rule easy to read.
Step 3: decide about text like '6'
Should '6' count? It looks like a number, but it is text. That is a choice you make on purpose. If you want to accept it, Number(v) turns text into a number, and gives NaN when the text isn't a number:
console.log(Number('6')); // 6
console.log(Number('two')); // NaN
console.log(Number('')); // 0
console.log(Number(' ')); // 0
console.log(Number(true)); // 1
Two lines need care. Empty or blank text turns into 0, so blank text needs its own check. And true turns into 1, which would let a checkbox sneak into a money total.
Step 4: the lenient version
Use one reduce that decides what to do with each value. Real numbers are added. Text is added only if it isn't blank and turns into a finite number. Everything else, including true, is skipped:
const mixed = [1, 'two', 3, null, 4.5, undefined, NaN, Infinity, true, '6'];
const sumLenient = (values) =>
values.reduce((n, v) => {
if (typeof v === 'number' && Number.isFinite(v)) return n + v;
if (typeof v === 'string' && v.trim() !== '' && Number.isFinite(Number(v))) return n + Number(v);
return n;
}, 0);
console.log(sumLenient(mixed)); // 14.5
console.log(sumLenient([1, true])); // 1
v.trim() removes spaces from both ends, so ' ' becomes '' and is skipped. The total is 8.5 plus the 6 from '6'.
The full solution
The answer panel has both versions and prints both totals, then shows why typeof alone isn't enough and what Number(true) gives. The checks confirm booleans, NaN and Infinity are kept out. Press Run to see the output.
const mixed = [1, 'two', 3, null, 4.5, undefined, NaN, Infinity, true, '6'];
// Strict: only real numbers. NaN, Infinity, booleans and numeric strings are out.
const sumStrict = (values) =>
values.filter((v) => typeof v === 'number' && Number.isFinite(v))
.reduce((n, v) => n + v, 0);
// Lenient: also accept strings that are entirely a number.
const sumLenient = (values) =>
values.reduce((n, v) => {
if (typeof v === 'number' && Number.isFinite(v)) return n + v;
if (typeof v === 'string' && v.trim() !== '' && Number.isFinite(Number(v))) return n + Number(v);
return n;
}, 0);
console.log('strict :', sumStrict(mixed));
console.log('lenient:', sumLenient(mixed));
// Why typeof alone is not enough:
console.log('typeof NaN :', typeof NaN);
console.log('typeof Infinity :', typeof Infinity);
// And why coercion is a bad default: true would become 1.
console.log('Number(true) is', Number(true));
Output
8 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('strict sum', sumStrict(mixed), 8.5);
test('lenient sum includes the numeric string', sumLenient(mixed), 14.5);
test('NaN is typed number but not finite', typeof NaN === 'number' && !Number.isFinite(NaN), true);
test('Infinity is excluded', sumStrict([1, Infinity]), 1);
test('booleans do not sneak in', sumStrict([1, true]), 1);
test('nor do they in the lenient version', sumLenient([1, true]), 1);
test('an empty list sums to zero', sumStrict([]), 0);
test('a list of no numbers sums to zero', sumStrict(['a', null]), 0);
typeof NaN === 'number' is the reason Number.isFinite exists. A single NaN in the list poisons the whole sum to NaN, and nothing warns you. Note also that both versions refuse true: JavaScript would happily coerce it to 1, and a total that silently counts checkboxes as money is worse than one that ignores them.
Common mistakes
- Trusting
typeof v === 'number'. It letsNaNandInfinitythrough, and oneNaNturns the whole sum intoNaN. - Letting JavaScript convert for you. Adding values with
+as they come turnstrueinto 1, and1 + '6'gives the text'16'. - Forgetting blank text.
Number('')is0, so a blank cell looks like a valid number unless you check for it.
Try it yourself
- Count how many values were skipped, and return both the total and the count.
- Make
sumLenientalso accept text with a comma, like'1,200'. (Hint: remove the commas before converting.) - Write
averageStrict(values)usingsumStrictand the number of finite numbers.