Published
Edited
Oct 9, 2019
4 stars
Insert cell
Insert cell
Insert cell
[10,1,2,5,4,5,6,7, 10, 1, 2].filter((item) => {
return item >= 5
})
Insert cell
md`When we are using reduce - we are taking a collection of items, and returning it to a single value. However, that single value could still be an array of items.

Recall, that when using .reduce - we can provide an accumulator - or the thing that will represent the final value that we are holding onto.

To implement a similar filter with reduce - we would want to check if the current value is >= 5, if so - add it to the accumulator, or what will turn into the final value.`
Insert cell

[10, 1, 2, 5, 4, 5, 6, 7, 10, 1, 2].reduce((acc, value) => {
if (value >= 5) {
return [...acc, value];
} else {
return acc;
}
}, []);

Insert cell
md `# Map

When we are mapping over an array - we are wanting to transform one value into another value, for example maybe doubling all of the numbers in the array`
Insert cell
[10, 1, 2, 5, 4, 5, 6, 7, 10, 1, 2].map(value => {
return value * 2;
});

Insert cell
md `Since reduce also operates over very item in the collection, we can return a doubled value into the accumulator:`
Insert cell
[10, 1, 2, 5, 4, 5, 6, 7, 10, 1, 2].reduce((acc, value) => {
return [...acc, value * 2];
}, []);

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