The map
method is great for creating data that maps directly to elements from an existing array. However, sometimes, the desired result takes on a different shape. To do this, we can use the reduce
method to accumulate values into a new form.
In this recipe, we'll take a look at how to use the reduce
method to transform data.
This recipe assumes that you already have a workspace that allows you to create and run ES modules in your browser. If you don't, refer to the first two chapters.
- Open your command-line application, and navigate to your workspace.
- Create a new folder named
10-05-reduce-to-transform-data
. - Create a
main.js
file that defines a newclass
namedRocket
that takes a constructor argumentname
and assigns it to an instance property:
// main.js class Rocket { constructor(name) { this.name = name; } }
- Create a
main
function with an array of nationality strings:
// main.js export function main() { const...