<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js'></script>
var $ = window.$;
var _ = window._;
var myArr = [1, 2, 1, 3, 1, 4];
var longArr = [];
for (let i = 0; i < 100000; i++) {
longArr.push(Math.floor(Math.random() * 100));
}
var result = $.unique( myArr );
var result2 = $.unique( longArr );
var result = _.uniq( myArr );
var result2 = _.uniq( longArr );
var flags = [],
output = [],
l = myArr.length,
i;
for (i = 0; i < l; i++) {
if (flags[myArr[i]]) continue;
flags[myArr[i]] = true;
output.push(myArr[i]);
}
var flags2 = [],
output2 = [],
l2 = myArr.length,
i2;
for (i2 = 0; i2 < l2; i2++) {
if (flags2[longArr[i2]]) continue;
flags2[longArr[i2]] = true;
output2.push(longArr[i2]);
}
var unique = myArr.filter(function (itm, i, a) {
return i == myArr.indexOf(itm);
});
var unique2 = longArr.filter(function (itm, i, a) {
return i == longArr.indexOf(itm);
});
var unique = [ (new Set(myArr))];
var unique2 = [ (new Set(longArr))];
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
jQuery | |
Lodash | |
Flags | |
JS Func | |
Set |
Test name | Executions per second |
---|---|
jQuery | 298.3 Ops/sec |
Lodash | 436.1 Ops/sec |
Flags | 306773.4 Ops/sec |
JS Func | 44.5 Ops/sec |
Set | 445.7 Ops/sec |
The provided JSON represents a benchmarking test for uniqueness in arrays, specifically the ability to remove duplicates from an array while preserving order.
Options Compared:
unique()
function to find unique elements in an array.uniq
function to achieve similar results.filter()
method with a custom function to remove duplicates, as well as a simple array spread operator (...(new Set())
) to find unique elements.Set
data structure to find unique elements in an array.Pros and Cons:
unique()
function can be easily integrated into existing projects.filter()
method and array spread operator.Library/Function Descriptions:
uniq()
function: Removes duplicate elements from an array while preserving order, returning a new array with unique values.unique()
function: A wrapper around Lodash's uniq
function, providing a convenient interface for finding unique elements in arrays.Special JavaScript Features/Syntax:
() => { }
)\
${...}``)[...set]
)Set
data structurePlease note that the array spread operator and Set data structure are supported in most modern browsers, but their behavior may vary across different environments.
Other Alternatives:
filter()
and checking for existence in the original array: Another manual implementation using JavaScript's built-in filter()
method with a custom callback function that checks if an element exists in the original array.Keep in mind that these alternatives might not be as efficient or concise as the provided benchmarking test, but can serve as useful reference points for further exploration.