Skip to content

Instantly share code, notes, and snippets.

@adamcee
Created November 8, 2024 17:38
Show Gist options
  • Select an option

  • Save adamcee/dc95e1e8962f6a4349c4a3ac432084c8 to your computer and use it in GitHub Desktop.

Select an option

Save adamcee/dc95e1e8962f6a4349c4a3ac432084c8 to your computer and use it in GitHub Desktop.
JS map and filter method chaining example
const fakePokemons = [
{ name: 'Charizar', type: 'fire', isCaught: true},
{ name: 'Pokemon', type: 'electric', isCaught: true},
{ name: 'Ditto', type: 'normal', isCaught: false},
{ name: 'Eevee', type: 'normal', isCaught: true},
]
/**
* Creates and returns a new object which has all the same
* properties as the poke object, but also has an `index` prop
* and a `foo` prop
*
* @param {*} poke pokemon object
* @param {*} index index int
* @returns object
*/
const addStuffToPokeObject = (poke, index) => {
return {
...poke, // destructures the obj into the object
index: index,
foo: 'hello'
}
};
const desired = 'normal'
const desiredPokemonsWithFoo = fakePokemons
.filter(p => p.type === desired)
.filter(p => p.isCaught === true)
// .map(addStuffToPokeObject);
.map((p, i) => ({ ...p, index: i, foo: 'hello'}))
console.log(desiredPokemonsWithFoo);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment