javascript 配列からnull以外のデータを抽出する
- 作成日 2021.06.17
- 更新日 2022.09.06
- javascript
- javascript

javascriptで、配列からnull以外のデータを抽出するサンプルコードを掲載してます。ブラウザはchromeを使用しています。
環境
- OS windows10 pro 64bit
- Apache 2.4.43
- ブラウザ chrome 104.0.5112.101
配列からnull以外のデータを抽出
配列からnull以外のデータを抽出するには、「filter」を使って「Object.prototype.toString.call」を使用することで可能です。
'use strict';
let arr = [null, 0, 1, [2], true, ['hoge', 'foo'], {}, new Date(), undefined, NaN]
arr = arr.filter( function (x) { return Object.prototype.toString.call(x) !== '[object Null]' } )
console.log( arr )
実行結果を確認すると、null以外のデータが取得されていることが確認できます。

また、以下のコードを、
arr = arr.filter( function (x) { return Object.prototype.toString.call(x) !== '[object Null]' } )
アロー関数を使用して、以下のように簡潔に記述することもできます。
arr = arr.filter((x) => { return Object.prototype.toString.call(x) !== '[object Null]' })
サンプルコード
以下は、
「実行」ボタンをクリックして、「null」以外のデータを取得して表示するサンプルコードとなります。
※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 = [null, 0, 1, [2], true, ['hoge', 'foo'], {}, new Date(), undefined, NaN];
disp(arr, "foo");
disp(arr.filter( (x) => { return Object.prototype.toString.call(x) !== '[object Null]' } ), "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>
実行結果を確認すると、null以外のデータが取得されていることが確認できます。

-
前の記事
php 配列同士をマージする 2021.06.16
-
次の記事
python numpyの配列の値を確認する 2021.06.17
コメントを書く