Created
August 30, 2019 13:48
-
-
Save wesleygrimes/c48c5a39fb43fd783f90df4394bcd351 to your computer and use it in GitHub Desktop.
JavaScript Arrays
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 heroes = [ | |
{ fullName: 'Spider-Man', heroId: 1 }, | |
{ fullName: 'Iron Man', heroId: 2 }, | |
]; | |
const alterEgos = [ | |
{ fullName: 'Peter Parker', heroId: 1 }, | |
{ fullName: 'Tony Stark', heroId: 2 }, | |
]; | |
// using for..of loop | |
const forLoopUnmaskedHeroes = []; | |
for (const h of heroes) { | |
const f = alterEgos.find(a => a.heroId === h.heroId); | |
forLoopUnmaskedHeroes.push({ | |
hero: h.fullName, | |
alterEgo: f.fullName, | |
}); | |
} | |
// using Array.forEach | |
const forEachUnmaskedHeroes = []; | |
heroes.forEach(h => { | |
const f = alterEgos.find(a => a.heroId === h.heroId); | |
forEachUnmaskedHeroes.push({ | |
hero: h.fullName, | |
alterEgo: f.fullName, | |
}); | |
}); | |
// using Array.map | |
const mapUnmaskedHeroes = heroes.map(h => { | |
const f = alterEgos.find(a => a.heroId === h.heroId); | |
return { | |
hero: h.fullName, | |
alterEgo: f.fullName, | |
}; | |
}); | |
console.log({ forEachUnmaskedHeroes, forLoopUnmaskedHeroes, mapUnmaskedHeroes }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment