简体   繁体   中英

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

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/lodash@4.17.10/lodash.min.js"></script> 

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) 

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/lodash@4.17.10/lodash.min.js"></script> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM