0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

2つの配列でvalueが一致したものを抽出

Last updated at Posted at 2020-01-31
  • 名前とチーム名を書いたプレイヤー一覧
  • 好きなチームを書いたファン一覧
  • ファンが好きなチームに所属しているプレイヤーを取得する
const playerList = [
  {
    id: 1,
    name: 'イチロー',
    team: 'マリナーズ',
  },
  {
    id: 2,
    name: '松井',
    team: 'ヤンキース',
  },
  {
    id: 3,
    name: 'マー君',
    team: 'ヤンキース',
  }
];

const fanList = [
  {
    id: 1,
    team: 'レッドソックス',
  },
  {
    id: 2,
    team: 'ヤンキース'
  },
  {
    id: 3,
    team: 'ジャイアンツ'
  }
];

const pupolarTeamList = fanList.map(fan => fan.team)
const popularPlayerList = playerList.filter(player => pupolarTeamList.includes(player.team));

console.log(popularPlayerList)

/*
[
  {
    id: 2,
    name: '松井',
    team: 'ヤンキース',
  },
  {
    id: 3,
    name: 'マー君',
    team: 'ヤンキース',
  }
]
*/

チームごとに分ける

  • ファンが好きなチームに所属しているプレイヤーをチームごとに分ける
const playerList = [
  {
    id: 1,
    name: 'イチロー',
    team: 'マリナーズ',
  },
  {
    id: 2,
    name: '松井',
    team: 'ヤンキース',
  },
  {
    id: 3,
    name: 'マー君',
    team: 'ヤンキース',
  }
];

const fanList = [
  {
    id: 1,
    team: 'レッドソックス',
  },
  {
    id: 2,
    team: 'ヤンキース'
  },
  {
    id: 3,
    team: 'ジャイアンツ'
  },
  {
    id: 4,
    team: 'マリナーズ'
  }
];

const pupolarTeamList = fanList.map(fan => fan.team)

let eachTeamPlayerList = [];
pupolarTeamList.forEach((pupolarTeam) => {
  const eachTeamPlayer = playerList.filter(player => playerTeam === pupolar.team);
  if (eachTeamPlayer.length) {
    eachTeamPlayerList.push(eachTeamPlayer);
  }
});

console.log(eachTeamPlayerList)

/*
[
  [
    {
      id: 2,
      name: '松井',
      team: 'ヤンキース',
    },
    {
      id: 3,
      name: 'マー君',
      team: 'ヤンキース',
    }
  ],
  [
    {
      id: 1,
      name: 'イチロー',
      team: 'マリナーズ',
    },
 ]
]
*/
0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?