Example:
This file contains 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
const cats = [ | |
{ name: 'Mojo', months: 84 }, | |
{ name: 'Mao-Mao', months: 34 }, | |
{ name: 'Waffles', months: 4 }, | |
{ name: 'Pickles', months: 6 } | |
] | |
var kittens = [] | |
for (var i = 0; i < cats.length; i++) { | |
if (cats[i].months < 7) { | |
kittens.push(cats[i].name) | |
} | |
} | |
console.log(kittens) |
This file contains 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
const isKitten = cat => cat.months < 7 | |
var kittens = [] | |
for (var i = 0; i < cats.length; i++) { | |
if (isKitten(cats[i])) { | |
kittens.push(cats[i].name) | |
} | |
} |
This file contains 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
const isKitten = cat => cat.months < 7 | |
const getName = cat => cat.name | |
var kittens = [] | |
for (var i = 0; i < cats.length; i++) { | |
if (isKitten(cats[i])) { | |
kittens.push(getName(cats[i])) | |
} | |
} |
And use filter and map methods
This file contains 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
const isKitten = cat => cat.months < 7 | |
const getName = cat => cat.name | |
const kittens = | |
cats.filter(isKitten) | |
.map(getName) | |
# Together | |
const isKitten = cat => cat.months < 7 | |
const getName = cat => cat.name | |
const getKittenNames = cats => | |
cats.filter(isKitten) | |
.map(getName) | |
const cats = [ | |
{ name: 'Mojo', months: 84 }, | |
{ name: 'Mao-Mao', months: 34 }, | |
{ name: 'Waffles', months: 4 }, | |
{ name: 'Pickles', months: 6 } | |
] | |
const kittens = getKittenNames(cats) | |
console.log(kittens) |
https://hackernoon.com/
Comments
Post a Comment