<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
var MyArr = Array.from({length: 40}, () => Math.floor(Math.random() * 40));
var myCopy = null;
myCopy = _.uniqBy(MyArr);
myCopy = new Set(MyArr)
myCopy = [ (new Set(MyArr))]
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash uniqBy | |
Set | |
Set spread |
Test name | Executions per second |
---|---|
Lodash uniqBy | 2780621.8 Ops/sec |
Set | 2626933.0 Ops/sec |
Set spread | 2447516.5 Ops/sec |
Let's dive into the explanation.
Overview
The provided JSON represents a JavaScript microbenchmark test case on MeasureThat.net. The benchmark tests three approaches to removing duplicate elements from an array: using Lodash's uniqBy
function, creating a new Set
object, and spreading the Set
object using the spread operator ([...]
).
Tested Approaches
uniqBy
function to remove duplicate elements from the array based on a custom comparison function.Set
object and adds each element of the original array to it. Since sets only store unique values, this approach removes duplicates automatically.Set
object and spreads its elements into an array using the spread operator ([...]
). The resulting array will have duplicate elements removed.Pros and Cons
Set
object directly, as it involves creating an intermediate array.Library: Lodash
Lodash (a library of functions for functional JavaScript programming) provides the uniqBy
function, which removes duplicate elements from an array based on a custom comparison function. The comparison function is used to determine whether two elements are equal or not.
Special JS Feature/Syntax: Spread Operator ([...] )
The spread operator is used in the "Set spread" approach to create a new array by spreading the elements of the Set
object. This syntax was introduced in ECMAScript 2015 (ES6) and allows for easy creation of arrays from other iterables, such as sets.
Other Alternatives
Set
object or Lodash's uniqBy
function, you could use the filter()
method to remove duplicate elements from an array.Object.values()
to get the values of an object (which can be used as a set), followed by Array.from()
to create an array from it.Here's some sample code using these alternatives:
// Using filter()
var myArr = [...]; // your array
var myCopy = myArr.filter((val, index, self) => {
return index === self.indexOf(val);
});
// Using Object.values() and Array.from()
var obj = { /* your object */ };
var myObjSet = new Set(Object.values(obj));
var myCopySpread = [...myObjSet];