There are 2 arrays in the array. There are objects in them. How can I find the one whose name is "Sneijder"?
const players = [
[
{
id: 1,
name: "Hagi",
},
{
id: 2,
name: "Carlos",
},
],
[
{
id: 3,
name: "Zidane",
},
{
id: 4,
name: "Sneijder",
},
],
];
3 Answers 3
You could flatten the array with flat
then find
your item in the resulting flattened array:
const players = [
[
{
id: 1,
name: "Hagi",
},
{
id: 2,
name: "Carlos",
},
],
[
{
id: 3,
name: "Zidane",
},
{
id: 4,
name: "Sneijder",
},
],
];
const player = players.flat().find((p) => p.name === "Sneijder")
console.log(player)
answered Dec 9, 2022 at 21:06
2 Comments
epascarello
you reinvented
flat()
and find()
spender
@epascarello hehe! You're right! Adjusted
You can use either of the 3 combinations or any different than these. All will give the same result but the complexity can be different for other examples having required object in the beginning or middle.
const players = [
[{
id: 1,
name: "Hagi",
},
{
id: 2,
name: "Carlos",
},
],
[{
id: 3,
name: "Zidane",
},
{
id: 4,
name: "Sneijder",
},
],
];
let player = "";
players.forEach(x => player = x.find(y => y.name === "Sneijder"));
console.log("Method 1", player);
player = players.flat().find(y => y.name === "Sneijder");
console.log("Method 2", player);
players.some(x => {
const [x1, x2] = x;
if (x1.name === "Sneijder") return player = x1;
if (x2.name === "Sneijder") return player = x2;
});
console.log("Method 3", player);
answered Dec 9, 2022 at 21:34
Comments
you can use Array.prototype.concat to merge arrays and then find by name
const sneijderObj = [].concat.apply([], players).find(x => x.name === 'Sneijder');
console.log(sneijderObj);
answered Dec 10, 2022 at 8:46
Comments
lang-js
players.flat().find(x => {return x.name=="Sneijder"})