<script src='https://cdn.jsdelivr.net/npm/lodash@4.17.10/lodash.min.js'></script>
var originalArray = [1, 2, 3, 4, 5, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7]
var l = new Set();
for (i of originalArray) {
l.add(i)
}
return l;
var l = [];
for (i of originalArray) {
l.push(i)
}
return _.uniq(l);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Set with add | |
Array with push then uniq |
Test name | Executions per second |
---|---|
Set with add | 5389393.0 Ops/sec |
Array with push then uniq | 7844240.5 Ops/sec |
The benchmark defined in the JSON compares two approaches for creating a unique list of elements from an array: using a Set
to hold unique values versus using an array combined with the Lodash library's uniq
function. Below is an explanation of the options being compared, their pros and cons, and other expert considerations.
Option 1: Using Set
var l = new Set();
for (i of originalArray) {
l.add(i);
}
return l;
Option 2: Using Array with Lodash's uniq
var l = [];
for (i of originalArray) {
l.push(i);
}
return _.uniq(l);
Set
data structure, which stores unique values. The add
method is called for each element in the originalArray
. Since Set
inherently prevents duplicate values, the end result is a collection of unique elements.Set
may use less memory than storing duplicates in an array before filtering.Set
, though it is widely supported in modern environments.uniq
function to filter out duplicates. Lodash is a utility library that enhances JavaScript with additional functionality, including functions for working with arrays, objects, and collections.In the benchmark results provided, the Array with push then uniq
approach achieved 7,844,240.5 executions per second, while the Set with add
method achieved 5,389,393.0 executions per second. This indicates that the array + Lodash approach was significantly faster in this particular run.
Set
. If working within an ecosystem reliant on Lodash, or if additional transformations or utility functions are needed later, the Lodash approach could be more favorable despite its overhead.Set
can make code more portable and reduce reliance on external libraries, which is often beneficial for maintainability.Other alternatives for removing duplicates from an array in JavaScript include:
filter
with indexOf
:const uniqueArray = originalArray.filter((value, index) => originalArray.indexOf(value) === index);
reduce
:const uniqueArray = originalArray.reduce((acc, value) => {
if (!acc.includes(value)) acc.push(value);
return acc;
}, []);
Set
:const uniqueArray = [...new Set(originalArray)];
Each of these methods has its trade-offs in terms of performance and readability, so the context of usage will largely dictate the best choice.