javascript 配列から文字列のみを抽出する

javascript 配列から文字列のみを抽出する

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

環境

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

文字列のみを抽出

文字列のみを取り出すには、「filter」を使って条件に「typeof」で「string」型を指定することで可能です。

'use strict';

let arr =['hoge', 'foo', 1, 2,'bar']

arr = arr.filter( function(x) { return typeof x === 'string' } )

console.log( arr )

実行結果を確認すると、文字列のみが取得されていることが確認できます。

また、以下のコードを、

arr = arr.filter( function(x) { return typeof x === 'string' } )

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

arr = arr.filter((x) => {return typeof x === 'string'})

また数値のみを抽出する場合は、以下となります。

'use strict';

let arr =['hoge', 'foo', 1, 2,'bar']

arr = arr.filter( function(x) { return typeof x === 'number' } )

console.log( arr ) // [1, 2]

サンプルコード

以下は、
「実行」ボタンをクリックして、配列から文字列のみを取得して表示するサンプルコードとなります。

※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 =['hoge', 'foo', 1, 2,'bar'];    

    disp(arr, "foo");

    disp(arr.filter(x => typeof x === 'string'), "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-green-500 text-lg mr-auto">元の配列</h1>
      <ul id="foo" class="font-semibold text-lg mr-auto"></ul>      
      
      <h1 class="font-semibold text-green-500 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-green-500 text-green-700 font-semibold hover:text-white py-2 px-4 border border-green-500 hover:border-transparent rounded">
        実行
      </button>

    </div>

  </div>
</body>

</html>

実行結果を確認すると、文字列のみが取得されていることが確認できます。