Stanislav Mayorov
Stanislav Mayorov

Reputation: 4452

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]             |
+---------+-----------------------+-----------------+

Upvotes: 0

Views: 1124

Answers (3)

Parth Raval
Parth Raval

Reputation: 4423

You can use _.differenceWith, and pass a comparator which compares two arrays, as in:

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

Upvotes: 0

Kristianmitk
Kristianmitk

Reputation: 4778

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>

Upvotes: 2

charlietfl
charlietfl

Reputation: 171679

This is a very simple filter operation using native Array#filter() and Array#includes()

let a = [1, 2, 3],
    b = [3, 4],
    unique = b.filter(e => !a.includes(e))

console.log(unique)

Or instead of includes() pass first array to a Set and use Set#has()

let a = new Set([1, 2, 3]),
  b = [3, 4],
  unique = b.filter(e => !a.has(e));

console.log(unique)

Upvotes: 1

Related Questions