LoginSignup
0
0

More than 5 years have passed since last update.

js オブジェクトの集まりが"truthy"であるか判定する

Last updated at Posted at 2017-01-30

お題

オブジェクトの集まり(第一引数)に項目(第二引数)が"truthy"であるか判定する。各オブジェクト全てで"truthy"であれば真を返す。
*truthy 真として振る舞う値("falsy" な値であるfalse,undefined,null,0,NaN,''以外)

function truthCheck(collection, pre) {
//write your code.
}

truthCheck([{"user": "Tinky-Winky", "sex": "male"}, {"user": "Dipsy", "sex": "male"}, {"user": "Laa-Laa", "sex": "female"}, {"user": "Po", "sex": "female"}], "sex");
//true

出力結果 例

truthCheck([{"user": "Tinky-Winky", "sex": "male"}, {"user": "Dipsy"}, {"user": "Laa-Laa", "sex": "female"}, {"user": "Po", "sex": "female"}], "sex") //false

truthCheck([{"name": "Pete", "onBoat": true}, {"name": "Repeat", "onBoat": true, "alias": "Repete"}, {"name": "FastFoward", "onBoat": true}], "onBoat") //true

truthCheck([{"single": ""}, {"single": "double"}], "single") //false

truthCheck([{"single": "double"}, {"single": NaN}], "single") //false

つかったもの

hasOwnProperty()
Boolean()
for in

考え方

・真を返すオブジェクトをカウントする変数を用意する。
・hasOwnProperty()でオブジェクトが第二引数を持っているか判定する
・Boolean()でオブジェクトの第二引数のプロパティが"truthy"であるか判定する
・上記二つにあてはまるかfor...in文で各オブジェクトにたいして実行する
・あてはまった場合、カウンターを増やしていく
・カウンターの数とオブジェクトの数が一致すれば全てのオブジェクトが"truthy"と言える。
その場合、真を返しておわり。

コード

function truthCheck(collection, pre) {
  var counter = 0;
  for (var c in collection) {
    if (collection[c].hasOwnProperty(pre) && collection[c][pre]) {
      counter++;
    }
  }
  return counter == collection.length;
}

その他コード

function truthCheck(collection, pre) {
  return collection.every(function (element) {
    return element.hasOwnProperty(pre) && element[pre];
  });
}

他にもコードが浮かんだ方、コメントお待ちしております。

0
0
2

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