Published
Edited
Sep 17, 2020
Insert cell
Insert cell
valuesArray = [{ val: 5 }, { val: 6 }, { val: 10 }];
Insert cell
Insert cell
usingReduce = valuesArray.reduce((acc, item) => {
return acc + item.val;
}, 0)
Insert cell
Insert cell
usingD3Sum = d3.sum(valuesArray, item => item.val)
Insert cell
Insert cell
function sum(values, valueof) {
// Initialize sum to 0 as we did in `usingReduce`
let sum = 0;
// If no valueof is specified, we assume it's an array of numbers
if (valueof === undefined) {
for (let value of values) {
// if value exists, convert it to a number if necessary (e.g. "8" --> 8)
if ((value = +value)) {
// Add the converted value to the sum
sum += value;
}
}
// valueof is provided and is expected to be a function
} else {
let index = -1;
for (let value of values) {
// if value exists, pass it to valueof function and convert it to a number if necessary (e.g. "8" --> 8)
if ((value = +valueof(value, ++index, values))) {
// Add the converted value to the sum
sum += value;
}
}
}
return sum;
}
Insert cell
Insert cell
d3 = require("d3@6")
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more