JS. Loop "for" dead



Example:
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)
Let's move check kitten to a new function
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)
}
}
Great! Let's move get name to another function
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
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