<script src='https://cdn.jsdelivr.net/npm/underscore@1.12.1/underscore-min.js'></script>
var a = [ 'a', 'b', 'c' ];
var b = [ 'b', 'd', 'a', 'e', 'f' ];
var c = _.union(a, b);
var a = [ 'a', 'b', 'c' ];
var b = [ 'b', 'd', 'a', 'e', 'f' ];
var c = Object.assign([], a, b);
var a = [ 'a', 'b', 'c' ];
var b = [ 'b', 'd', 'a', 'e', 'f' ];
var c = _.uniq([a, b]);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
underscore union | |
object.assign | |
underscore uniq spread |
Test name | Executions per second |
---|---|
underscore union | 3007483.0 Ops/sec |
object.assign | 530632.6 Ops/sec |
underscore uniq spread | 3511533.5 Ops/sec |
This benchmark compares three different methods for finding the unique elements in two arrays:
1. underscore union
:
_.union()
function from the Underscore.js library. This library is designed to provide utility functions for working with JavaScript collections, including arrays.2. object.assign
:
Object.assign()
and combines the elements of both input arrays._.union()
. Can be harder to read and understand for its specific purpose.3. underscore uniq spread
:
_.uniq()
function from Underscore.js combined with the spread operator (...
) to create a new array containing unique elements.Other Alternatives:
Set
object can be used to efficiently find the union of arrays. Convert each array into a Set, then use the intersection()
method or logic like: const setA = new Set(arrayA);
const setB = new Set(arrayB);
const uniqueElements = [...new Set([...setA, ...setB])];
filter
and indexOf
: You can combine the filter
method to remove duplicates and the indexOf
method for checking existence within an array. This is less efficient than the alternatives but demonstrates a purely native JavaScript approach.Important Considerations:
underscore uniq spread
and underscore union
are significantly faster than object.assign
. For large datasets, performance differences become more noticeable.object.assign
is straightforward, using library functions like _.union()
can make your code more concise and readable, especially for common tasks like array manipulation.Let me know if you have any other questions!