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

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more