const array = [
{
username: "john",
team: "red",
score: 5,
items: ["ball", "book", "pen"]
},
{
username: "becky",
team: "blue",
score: 10,
items: ["tape", "backpack", "pen"]
},
{
username: "susy",
team: "red",
score: 55,
items: ["ball", "eraser", "pen"]
},
{
username: "tyson",
team: "green",
score: 1,
items: ["book", "pen"]
},
];
I have the above array. I have filtered the users that are in team red. Is there a way to return only the usernames of all users in team red instead of returning the whole data entry? So the output should be "[ John, Susy ]". I have this code so far.
const filterArray = array.filter(user3 => {
return user3.team === "red";
})
Since the result of filter method is an array, you can map over your filtered array and extract just username property, like this:
const array = [ { username: "john", team: "red", score: 5, items: ["ball", "book", "pen"] }, { username: "becky", team: "blue", score: 10, items: ["tape", "backpack", "pen"] }, { username: "susy", team: "red", score: 55, items: ["ball", "eraser", "pen"] }, { username: "tyson", team: "green", score: 1, items: ["book", "pen"] },];
const filterArray = array.filter(({team}) => team === "red").map(({username}) => username)
console.log(filterArray)
You can map the filtered array to only have the username property in it.
const array=[{username:"john",team:"red",score:5,items:["ball","book","pen"]},{username:"becky",team:"blue",score:10,items:["tape","backpack","pen"]},{username:"susy",team:"red",score:55,items:["ball","eraser","pen"]},{username:"tyson",team:"green",score:1,items:["book","pen"]}];
const filterArray = array.filter(user3 => {
return user3.team === "red";
})
const onlyNames = filterArray.map(u => u.username)
console.log(onlyNames)