javascript 配列データの一部の値が条件を満たしているかを判定する

javascript 配列データの一部の値が条件を満たしているかを判定する

javascriptで、someを使用して、配列データの一部の値が条件を満たしているかを判定するサンプルコードを記述してます。

環境

  • OS windows10 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 100.0.4896.75

some使い方

someを使用すると、配列データの一部の値が条件を満たしているかを判定することが可能です。

'use strict';

const arr = [1, 2, 3, 4, 5];

const result = arr.some((value, index, array) => {
  return (value > 1);
});

console.log(result); // true

また、アロー関数を使用すると以下のように、1行で記述することが可能です。

const arr = [1, 2, 3, 4, 5];

console.log(arr.some((value, index, array) => value >  1)); // true

使用していない引数も省略できます。

const arr = [1, 2, 3, 4, 5];

console.log(arr.some((value) => value >  1)); // true

サンプルコード

以下は、
「実行」ボタンをクリックすると、ランダムな3個の配列を生成して、
指定した条件である、配列内の一部の値が「7」より大きければ「true」それ以外は「false」を表示する
サンプルコードとなります。

※cssには「bootstrap5」を使用してます。「bootstrap5」は、IEのサポートを7終了してます。関数はアロー関数を使用してます。

<!DOCTYPE html>
<html lang="ja">

<head>
  <meta charset="utf-8">
  <title>mebeeサンプル</title>
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css">
</head>

<style>
  .main {
    margin: 0 auto;
    margin-top: 200px;
    display: flex;
    flex-direction: column;
    align-items: center;
    font-size: 30px;
  }
</style>
<script>

  const hoge = () => {

    // ランダムな3個の整数1桁の配列を生成
    const arr = Array(3).fill().map(x => ~~(Math.random() * 10));

    // 生成した配列を表示
    disp(arr, "rand");

    // 配列内の値が1つでも7より大きければtrue それ以外はfalse
    result.innerHTML = arr.some(x => x > 7) // document.getElementById('result');を省略

  }

  //フロントに表示する関数
  const disp = (arr, id) =>  {
    let text = [];
    // for ofを使用
    for (let item of arr) {
      text.push('<li class="list-group-item">' + item + '</li>');
    }
    //innerHTMLを使用して表示    
    document.getElementById(id).innerHTML = text.join('');
  }

  window.onload = () => {
    // クリックイベントを登録
    btn.onclick = () => { hoge(); }; // document.getElementById('btn');を省略
  }

</script>

<body>
  <div class="main container">

    <h2><span class="badge bg-success">ランダムな配列</span></h2>
    <ul id="rand" class="list-group list-group-flush"></ul>

    <h2><span id="result" class="badge bg-success">結果</span></h2>

    <div class="row">
      <button id="btn" type="button" class="btn btn-warning">
        実行
      </button>
    </div>

  </div>

</body>

</html>

判定されていることが確認できます。