Reputation: 57
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",
},
],
];
Upvotes: 1
Views: 71
Reputation: 651
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);
Upvotes: 0
Reputation: 632
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);
Upvotes: 1
Reputation: 120400
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)
Upvotes: 2