LoginSignup
0
0

More than 3 years have passed since last update.

JavaScript 連想配列のキーが「全部一致している」や「一部含まれてる」を判定したいとき

Last updated at Posted at 2020-05-01

こんな感じの連想配列があって、「全部フルーツ?」とか「ドリンクが含まれてる?」とか調べたいとき

const foods = [
  {
    id: 1,
    name: 'Apple',
    category: 'fluits'
  },
  {
    id: 2,
    name: 'Banana',
    category: 'fluits'
  },
  {
    id: 3,
    name: 'Grape',
    category: 'fluits'
  },
  {
    id: 4,
    name: 'Carot',
    category: 'vegetables'
  },
  {
    id: 5,
    name: 'Tea',
    category: 'drink'
  }
]

everyとかsomeを使う👍


// foodsが全部フルーツか?
const matchFluits = foods.every(item => item.category === 'fluits') // false

// foodsにドリンクが含まれているか?
const hasDrink = foods.some(item => item.category === 'drink') // true

filterとかforEachを使う👎


// 'drink'と一致する要素を取り出してから個数をBooleanでキャスト
// 取り出した要素が0個ならfalseにキャストされる
// ゴリゴリのゴリラ実装🦍
const hasDrink = (Boolean)(foods.filter(item => item.category === 'drink').length)

// forEachで
let hasDrink = false
foods.forEach(item => {
  if (item.category === 'drink') {
    hasDrink = true
    return
  }
})

ところで

全部一致してる?みたいな変数ってどんな名前にするのがいいのだろう🤔🤔🤔
hasDrinkcontainsDrinkの方がいい気もする

MDN

Array.prototype.every()
Array.prototype.some()

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