0
2

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 1 year has passed since last update.

配列の中のオブジェクト中の配列とある配列を比較して、同じ要素があるものを取得する

Last updated at Posted at 2022-10-25

やりたいこと

[
  {
    email: 'b@gmail.com',
    tags: ['VIP', 'male'],
  },
  {
    email: 'a@gmail.com',
    tags: ['VIP', 'male', 'cool'],
  },
  {
    email: 'c@gmail.com',
    tags: ['VIP', 'female'],
  },
  {
    email: 'd@gmail.com',
    tags: ['female'],
  },
];

これを

['female']

と比較して、femaleが入っている要素だけ取得したい

[
  {
    email: 'c@gmail.com',
    tags: ['VIP', 'female'],
  },
  {
    email: 'd@gmail.com',
    tags: ['female'],
  },
];

解決方法

const customers = [
  {
    email: 'b@gmail.com',
    tags: ['VIP', 'male'],
  },
  {
    email: 'a@gmail.com',
    tags: ['VIP', 'male', 'cool'],
  },
  {
    email: 'c@gmail.com',
    tags: ['VIP', 'female'],
  },
  {
    email: 'd@gmail.com',
    tags: ['female'],
  },
];

const compareData = ['female', 'VIP'];

const result = customers.filter((el) =>
  el.tags.some((r) => compareData.includes(r))
);

console.log(result);

0
2
0

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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?