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>

メソッドを複数の配列に適応して重複しているデータを取り除く

メソッドを複数の配列に適応して重複しているデータを取り除くには、「_.xorBy」を使用します。

'use strict';

const arr1 = [
  1.11,
  2.22,
  3.33
]

const arr2 = [
  1.25,
  2.5
]

const arr3 = [
  3.85,
  5.15
]

console.log(
  _.xorBy(arr1, arr2, arr3, Math.floor)
);

const arr4 = [
  { 'name': 'm', 'age': 20 },
  { 'name': 'e', 'age': 25 },
  { 'name': 'b', 'age': 25 },
  { 'name': 'e', 'age': 55 },
  { 'name': 'e', 'age': 55 }
]

const arr5 = [
  { 'name': 'm', 'age': 21 },
  { 'name': 'e', 'age': 25 },
  { 'name': 'b', 'age': 25 },
  { 'name': 'e', 'age': 55 },
  { 'name': 'e', 'age': 56 }
]

console.log(
  _.xorBy(arr4, arr5, 'age')
);

実行結果を確認すると、メソッドを適応後に、重複しているデータが取り除かれて取得されていることが確認できます。

サンプルコード

以下は、
「実行」ボタンをクリックして、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>

  const hoge = () => {

    const arr1 = [
      -1,
      -2,
      3
    ]

    const arr2 = [
      1,
      2
    ]

    disp(arr1, "foo");
    disp(arr2, "bar");

    disp(_.xorBy(arr1, arr2, Math.abs), "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-indigo-500 text-lg mr-auto">元の配列</h1>
      <ul id="foo" class="font-semibold text-lg mr-auto"></ul>

      <h1 class="font-semibold text-indigo-500 text-lg mr-auto">元の配列2</h1>
      <ul id="bar" class="font-semibold text-lg mr-auto"></ul>

      <h1 class="font-semibold text-indigo-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-indigo-500 text-indigo-700 font-semibold hover:text-white py-2 px-4 border border-indigo-500 hover:border-transparent rounded">
        実行
      </button>

    </div>

  </div>
</body>

</html>

実行結果を確認すると、除かれた配列データがフロントに表示されていることが確認できます。