Considering the following array which includes several objects within it, I tried to get specific values in one single array.To put it delicately,I wanted to pull out the name of people who were in the "red" team.
//
const array = [
{
username: "Mike",
team: "red",
score: 20,
items: ["bat", "book", "gloves"]
},
{
username: "Moe",
team: "blue",
score: 30,
items: ["cellphone", "backpack", "cards"]
},
{
username: "Ellie",
team: "red",
score: 15,
items: ["ball", "canteen", "crayon"]
},
{
username: "little_joe",
team: "green",
score: 1,
items: ["book", "pencil"]
},
];
//using filter method :
const filterArray=array.filter((num)=>{ if (num.team==="red" ){ return num.username}});
console.log(filterArray);
//result : an array including two objects full of unwanted values.
What should I do to get one single array with only desired value ( not two big objects) ?
I'm trying to get an array like this : (2)►[Mike,Ellie]
One way to do this would be to use Array.prototype.filter
and Array.prototype.map
. However, the preferred way would be to use Array.prototype.reduce
as it will be much more efficient.
Like this:
const array = [{
username: "Mike",
team: "red",
score: 20,
items: ["bat", "book", "gloves"]
},
{
username: "Moe",
team: "blue",
score: 30,
items: ["cellphone", "backpack", "cards"]
},
{
username: "Ellie",
team: "red",
score: 15,
items: ["ball", "canteen", "crayon"]
},
{
username: "little_joe",
team: "green",
score: 1,
items: ["book", "pencil"]
},
];
const newArray = array.reduce((n, val) => {
if(val.team == "red") n.push(val.username);
return n;
}, []);
console.log(newArray);
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments