I have an object:
const animals = [
{name: 'Fluffy', species: 'cat'},
{name: 'Crinkle', species: 'rabbit'},
{name: 'Wally', species: 'dog'},
{name: 'Roo', species: 'dog'},
{name: 'Felix', species: 'cat'},
]
I want to use a higher order function such as the filter() method to take the array of animal objects and return an array with just the names of all the dogs ie ["Wally", "Roo"]
. My code at the moment returns an array containing the entire object with the species dog in it. See below:
const dogArray = animals.filter(function(animal) {
return animal.species === 'dog';
})
return dogArray;
// returns
// [{name: "Wally", species: "dog"},
// { name: "Roo", species: "dog"}]
Just map the elements of the filtered array to their name property:
const animals = [ {name: 'Fluffy', species: 'cat'}, {name: 'Crinkle', species: 'rabbit'}, {name: 'Wally', species: 'dog'}, {name: 'Roo', species: 'dog'}, {name: 'Felix', species: 'cat'}, ] const dogArray = animals.filter(animal => animal.species === 'dog'); console.log(dogArray.map(dog => dog.name));
Or combine the two into one reduce:
const animals = [ {name: 'Fluffy', species: 'cat'}, {name: 'Crinkle', species: 'rabbit'}, {name: 'Wally', species: 'dog'}, {name: 'Roo', species: 'dog'}, {name: 'Felix', species: 'cat'}, ] let dogArray = animals.reduce((dogs, animal) => { if (animal.species === "dog") dogs.push(animal.name); return dogs; }, []); console.log(dogArray)
You could map the property with a destructuring .
const animals = [{ name: 'Fluffy', species: 'cat' }, { name: 'Crinkle', species: 'rabbit' }, { name: 'Wally', species: 'dog' }, { name: 'Roo', species: 'dog' }, { name: 'Felix', species: 'cat' }] dogArray = animals .filter(({ species }) => species === 'dog') .map(({ name }) => name); console.log(dogArray);
Create an empty array, iterate over the existing dogArray
using a for
loop, push the names into the new array, and return the new array.
const dogArray = animals.filter(function(animal) {
return animal.species === 'dog';
})
let dogNames = [];
for (let i in dogArray) {
dogNames.push(dogArray[i].name);
}
return dogNames;
const animals = [ {name: 'Fluffy', species: 'cat'}, {name: 'Crinkle', species: 'rabbit'}, {name: 'Wally', species: 'dog'}, {name: 'Roo', species: 'dog'}, {name: 'Felix', species: 'cat'}, ] var result = animals.filter(val=>val.species=="dog").map(({name})=>name); console.log(result);
You can use .filter()
followed by .map()
:
const animals = [ {name: 'Fluffy', species: 'cat'}, {name: 'Crinkle', species: 'rabbit'}, {name: 'Wally', species: 'dog'}, {name: 'Roo', species: 'dog'}, {name: 'Felix', species: 'cat'}, ]; const dogNames = animals .filter(animal => animal.species === 'dog') .map(dog => dog.name); console.log(dogNames);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.