Skip to main content Accessibility Feedback

Chaining array methods in vanilla JS

This week, we’ve been looking at the various array methods and how they work under-the-hood. Because many of them return an array, they can be chained together.

An example

Let’s again look at our list of Wizards.

var wizards = [
	{
		name: 'Harry Potter',
		house: 'Gryfindor'
	},
	{
		name: 'Cedric Diggory',
		house: 'Hufflepuff'
	},
	{
		name: 'Tonks',
		house: 'Hufflepuff'
	},
	{
		name: 'Ronald Weasley',
		house: 'Gryfindor'
	},
	{
		name: 'Hermione Granger',
		house: 'Gryfindor'
	}
];

Let’s say you wanted to get an array containing only the names of wizards from Hufflepuff.

Chaining Array.filter() and Array.map()

We can use Array.filter() to reduce the list to only wizards in Huffelpuff, and then Array.map() to create a new array of only names.

var hufflepuff = wizards.filter(function (wizard) {
	return wizard.house === 'Hufflepuff';
}).map(function (wizard) {
	return wizard.name;
});

Here’s a demo.