Calculates the sum of values in an array.
If a key is provided, the value from that property will be used for each item. Otherwise, items themselves are converted to numbers.
key
Supports nested arrays of values.
The type of items in the array.
The array of items to sum.
Optional
Optional property key used to extract numeric values from each item.
The sum of all numeric values.
Values are converted using Number(). Non-numeric values will result in NaN.
Number()
NaN
sum([1, 2, 3])// 6 Copy
sum([1, 2, 3])// 6
sum([[1, 2], [3, 4]])// 10 Copy
sum([[1, 2], [3, 4]])// 10
sum([1, [2, [3, 4]]])// 10 Copy
sum([1, [2, [3, 4]]])// 10
sum([{ price: 10 }, { price: 20 }], 'price')// 30 Copy
sum([{ price: 10 }, { price: 20 }], 'price')// 30
sum([{ price: 10 }, [{ price: 20 }]], 'price')// 30 Copy
sum([{ price: 10 }, [{ price: 20 }]], 'price')// 30
sum([{ score: 5 }, { score: 7 }, { score: 8 }], 'score')// 20 Copy
sum([{ score: 5 }, { score: 7 }, { score: 8 }], 'score')// 20
Calculates the sum of values in an array.
If a
keyis provided, the value from that property will be used for each item. Otherwise, items themselves are converted to numbers.Supports nested arrays of values.