javascript lodashを使って配列の一番最後の値を削除する

javascript lodashを使って配列の一番最後の値を削除する

javascriptで、lodashを使って配列の一番最後の値を削除するサンプルコードを掲載してます。ブラウザはchromeを使用しています。

環境

  • OS windows10 pro 64bit
  • Apache 2.4.43
  • lodash 4.17.21
  • ブラウザ chrome 91.0.4472.77

lodash使用

こちらのサイトから最新版を確認して、CDN版を使用してます。

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>

配列の一番最後の値を削除

配列の一番最後の値を削除するには、「_.initial」を使用します。

'use strict';

let arr = [
  "aaa",
  "bbb",
  "ccc"
]

console.log(
  _.initial(arr) // ["aaa", "bbb"]
);

arr = [
  ['a', 1],
  ['b', 2],
  ['c', 3]
]

console.log(
  _.initial(arr) // [["a", 1],["b", 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">
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>
</head>

<script>
  // ランダムな「0~9」までの5個の配列を用意
  const arr = Array(5).fill().map(x => ~~(Math.random() * 10));

  const hoge = () => {
    disp( _.initial(arr), "foo");
  }

  //フロントに表示する関数
  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 = () => {

    disp( arr, "foo");

    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">

      <ul id="foo" class="font-semibold text-lg mr-auto"></ul>

      <h1 id="bar" class="font-semibold text-lg mr-auto"></h1>

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

    </div>

  </div>
</body>

</html>

実行結果を確認すると、最後の値が削除されて表示されていることが確認できます。