1

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",
    },
  ],
];

1
  • 2
    players.flat().find(x => {return x.name=="Sneijder"}) Commented Dec 9, 2022 at 21:07

3 Answers 3

2

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)

Sign up to request clarification or add additional context in comments.

2 Comments

you reinvented flat() and find()
@epascarello hehe! You're right! Adjusted
1

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);

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.