Created
October 1, 2020 16:12
-
-
Save tjkhara/2f97a5d963e543fd4ea662dcb7b4440e to your computer and use it in GitHub Desktop.
map and filter examples
This file contains hidden or 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
| let pets = [ | |
| {name: "meow", species: "cat", age: 2}, | |
| {name: "miles", species: "dog", age: 10}, | |
| {name: "gogo", species: "mouse", age: 1}, | |
| {name: "popo", species: "dog", age: 1} | |
| ] | |
| // x = pets.push({name: "Puppster", species: "dog", age: 4}) | |
| // console.log(x) | |
| // let y = pets.map(nameOnly) | |
| function nameOnly(dict) { | |
| return dict["name"] | |
| } | |
| // console.log(y) | |
| // filter | |
| let dogs = pets.filter(onlyDogs) | |
| function onlyDogs(x){ | |
| return x.species == "dog" | |
| } | |
| // console.log(dogs) | |
| function onlyBabies(x){ | |
| return x.age < 3 | |
| } | |
| let babies = pets.filter(onlyBabies) | |
| // console.log(babies) | |
| // Now to get only baby dogs | |
| let babyDogNames = pets.filter(onlyDogs).filter(onlyBabies).map(nameOnly) | |
| console.log(babyDogNames) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment