Using Array.reduce to transform data
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.
Getting ready
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.
How to do it...
- Open your command-line application, and navigate to your workspace.
- Create a new folder named
10-05-reduce-to-transform-data. - Create a
main.jsfile that defines a newclassnamedRocketthat takes a constructor argumentnameand assigns it to an instance property:
// main.js
class Rocket {
constructor(name) {
this.name = name;
}
} - Create a
mainfunction with an array of nationality strings:
// main.js
export function main() {
const...