Iterating Arrays

Array

var items = [
	{ name: 'ted' }, 
	{ name: 'ted' }, 
	{ name: 'bob' }, 
	{ name: 'fred' }
]

An array of objects.

forEach

items.forEach(function(item) {
	// do something
})

Do something with each item in an array.

map

var names = items.map(function(item) {
	return item.name
})

Build a new array from each item in an array.

[
	'ted', 
	'ted', 
	'bob', 
	'fred'
]

filter

names = names.filter(function(name) {
	return name.match(/ed$/)
});

Filter the items in an array.

[
	'ted', 
	'ted', 
	'fred'
]

reduce

var teds = names.reduce(function(count, name) {
	return (name == 'ted') ? count + 1 : count
}, 0);

Summarise the items in an array.

2