<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.5/lodash.min.js"></script>
var itemsCount = 1e2;
var items = Array.from({ length: itemsCount }, () => Math.floor(Math.random() * itemsCount));
items.reduce((list, item) => list.indexOf(item) > -1 ? list : [list, item], []);
_.uniq(items)
function unique(arr) {
var hash = {}, result = [];
for ( var i = 0, l = arr.length; i < l; ++i ) {
if ( !hash.hasOwnProperty(arr[i]) ) { //it works with objects! in FF, at least
hash[ arr[i] ] = true;
result.push(arr[i]);
}
}
return result;
}
unique(items)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Javascript Array.reduce/Array.indexOf | |
Lodash Uniq | |
function unique(arr) |
Test name | Executions per second |
---|---|
Javascript Array.reduce/Array.indexOf | 91058.1 Ops/sec |
Lodash Uniq | 262464.8 Ops/sec |
function unique(arr) | 340386.9 Ops/sec |
Overview of the Benchmark
The provided JSON represents a JavaScript benchmark that compares three approaches for creating an array with unique values: Array.reduce()
with Array.indexOf
, Lodash's uniq
function, and a custom implementation using an object hash.
Approaches Compared
reduce()
method to iterate over the array and indexOf()
to check for existing values. If a value is not found in the array, it's added to the result.uniq
function that removes duplicates from an array. This implementation simply calls this function on the input array.Pros and Cons
indexOf()
inside the loop, which can lead to poor performance for large arrays.Library and Its Purpose
Lodash is a popular JavaScript utility library that provides various functions for tasks such as array manipulation, string manipulation, and more. In this benchmark, Lodash's uniq
function is used to remove duplicates from an array.
Special JS Feature or Syntax
This benchmark does not explicitly use any special JavaScript features or syntax beyond the standard ECMAScript features supported by most modern browsers.
Other Alternatives
Set
data structure to keep track of unique values. This approach is more concise and efficient than the custom implementation.Promise.all()
Method: If you need to process an array in parallel, you could use the Promise.all()
method to create an array of promises that resolve to the unique values.Overall, this benchmark provides a good comparison of three approaches for creating an array with unique values, highlighting the trade-offs between simplicity, performance, and dependency management.