Home > database >  compare two array and put a status in an other array if it exist or not
compare two array and put a status in an other array if it exist or not

Time:06-15

so i have an array with all the players and one with only the one that are selected and i want to have an other array with the status if he is selected or not. i tried comparing and pushing the element with the status but didnt achieve what i wanted.

here are the arrays

  const all = [
    {
      playerId: '294',
      firstName: 'MMM',
    },
    {
      playerId: '295',
      firstName: 'arkiv',
    },
    {
      playerId: '296',
      firstName: 'julio',
    },
    {
      playerId: '297',
      firstName: 'sss',
    },
  ];

const selected = [
    {
      playerId: '296',
      firstName: 'julio',
    },
    {
      playerId: '297',
      firstName: 'sss',
    },
  ];

and this is what i want to achive

  const res = [
    { playerId: '294', firstName: 'MMM', status: false },
    { playerId: '295', firstName: 'arkiv', status: false },
    { playerId: '296', firstName: 'julio', status: true },
    { playerId: '297', firstName: 'sss', status: true },
  ];

i set up an environment to work here: https://stackblitz.com/edit/react-lkcqcd?file=src/App.js

thanks for attention!

CodePudding user response:

You can use Array#some to check if the id of the player is in the selected array.

const all=[{playerId:'294',firstName:'MMM',},{playerId:'295',firstName:'arkiv',},{playerId:'296',firstName:'julio',},{playerId:'297',firstName:'sss',},],selected=[{playerId:'296',firstName:'julio',},{playerId:'297',firstName:'sss',},];
all.forEach(player => player.status = 
              selected.some(x => x.playerId === player.playerId));
console.log(all);

CodePudding user response:

You can create a Set of selected players and using this set you can add the status field.

const 
  all = [{ playerId: "294", firstName: "MMM" }, { playerId: "295", firstName: "arkiv" }, { playerId: "296", firstName: "julio" }, { playerId: "297", firstName: "sss" }],
  selected = [{ playerId: "296", firstName: "julio" }, { playerId: "297", firstName: "sss" }],
  selectedSet = new Set(selected.map((player) => player.playerId)),
  res = all.map((player) => ({ ...player, status: selectedSet.has(player.playerId) }));

console.log(res);

You can also use Array.prototype.find instead of creating a set but this wouldn't be optimal unless the size of the selected array is quite small.

const 
  all = [{ playerId: "294", firstName: "MMM" }, { playerId: "295", firstName: "arkiv" }, { playerId: "296", firstName: "julio" }, { playerId: "297", firstName: "sss" }],
  selected = [{ playerId: "296", firstName: "julio" }, { playerId: "297", firstName: "sss" }],
  res = all.map((player) => ({
    ...player,
    status: !!selected.find((selPlayer) => selPlayer.playerId === player.playerId),
  }));

console.log(res);

  • Related