Search code examples
javascriptlodash

Compare two different length arrays using lodash


How to compare two arrays with different length using lodash? The first array contains existing element, the second one contains new and existing element. How can I get new element using lodash?

+---------+-----------------------+-----------------+
| Existing| Source of new element | Expected result |
+---------+-----------------------+-----------------+
| []      | [1]                   | [1]             |
| [1,2]   | [3,4]                 | [3, 4]          |
| [1,2,3] | [3,4]                 | [4]             |
+---------+-----------------------+-----------------+

Solution

  • I don't understand why you need lodash for it as its pretty simple done with Array#filter() as already suggested, but still if you want to rely on lodash then use _.difference().

    const
      a = [1, 2, 3],
      b = [3, 4];
      
      console.log(_.difference(b, a));
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>