Created
October 23, 2016 08:26
-
-
Save dnasca/fb70d8bcb217fb30152b0ae2b66a66a1 to your computer and use it in GitHub Desktop.
using map versus for iteration
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var foods = [ | |
{ name: 'brocolli', type: 'vegetable' }, | |
{ name: 'spinach', type: 'vegetable' }, | |
{ name: 'apple', type: 'fruit' }, | |
{ name: 'tomato', type: 'fruit' }, | |
{ name: 'bread', type: 'grain' }, | |
{ name: 'beef', type: 'meat' }, | |
{ name: 'chicken', type: 'meat' }, | |
] | |
// for iteration | |
var names = [] | |
for (var i = 0; i < foods.length; i++ ) { | |
names.push(foods[i].name) | |
} | |
// map es5 | |
var names = foods.map(function(food){ | |
return food.name | |
}) | |
// map es6 | |
let names = foods.map((food) => return food.name) //one liners do not require 'return' | |
// final functional form | |
let names = foods.map((x) => x.name) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment