Skip to content

Instantly share code, notes, and snippets.

@wesleygrimes
Created August 30, 2019 13:48
Show Gist options
  • Save wesleygrimes/c48c5a39fb43fd783f90df4394bcd351 to your computer and use it in GitHub Desktop.
Save wesleygrimes/c48c5a39fb43fd783f90df4394bcd351 to your computer and use it in GitHub Desktop.
JavaScript Arrays
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