javascript 配列からNaN以外のデータを抽出する

javascript 配列からNaN以外のデータを抽出する

javascriptで、配列からNaN以外のデータを抽出するサンプルコードを掲載してます。ブラウザはchromeを使用しています。

環境

  • OS windows11 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 104.0.5112.101

配列からNaN以外のデータを抽出

配列からNaN以外のデータを抽出するには、「filter」を使って「自身」と「自身」を比較することで可能です。
※「Nan === NaN」は「false」になります。

'use strict';

let arr = [NaN, 0, 1, [2], true , {}, new Date(), undefined, null ]

arr = arr.filter(function (x) { return x === x })

console.log( arr )

実行結果を確認すると、Nan以外のデータが取得されていることが確認できます。

また、以下のコードを、

arr = arr.filter(function (x) { return x === x })

アロー関数を使用して、以下のように簡潔に記述することもできます。

arr = arr.filter((x) => { return x === x })

また、別の方法として「Number.isNaN」を使用して判定することも可能です。

arr = arr.filter((x) => { return !Number.isNaN(x) })

サンプルコード

以下は、
「実行」ボタンをクリックして、NaN以外のデータを取得して表示するサンプルコードとなります。

※cssには「tailwind」を使用して、アロー関数で関数は定義してます。

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

<head>
  <meta charset="utf-8">
  <title>mebeeサンプル</title>
  <link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet">
</head>

<script>

  const hoge = () => {
    
    const arr =[NaN, 0, 1, [2], true , {}, new Date(), undefined, null ];

    disp(arr, "foo");

    disp(arr.filter(x => !Number.isNaN(x)), "fuga");

  }

  //フロントに表示する関数
  const disp = (arr, id) => {

    let text = [];

    arr.forEach((x, i) => text.push('<li class="list-group-item">' + arr[i] + '</li>'))

    document.getElementById(id).innerHTML = text.join('');

  }

  window.onload = () => {

    btn.onclick = () => { hoge() };

  }

</script>

<body>
  <div class="container mx-auto my-56 w-64 px-4">

    <div id="sample" class="flex flex-col justify-center">
      
      <h1 class="font-semibold text-pink-700 text-lg mr-auto">元の配列</h1>
      <ul id="foo" class="font-semibold text-lg mr-auto"></ul>      
      
      <h1 class="font-semibold text-pink-700 text-lg mr-auto">実行結果</h1>
      <ul id="fuga" class="font-semibold text-lg mr-auto"></ul>

      <button id="btn"
        class="mb-2 md:mb-0 bg-transparent hover:bg-pink-700 text-pink-900 font-semibold hover:text-white py-2 px-4 border border-pink-700 hover:border-transparent rounded">
        実行
      </button>

    </div>

  </div>
</body>

</html>

実行結果を確認すると、NaN以外のデータが取得されていることが確認できます。