<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
var arr = [
{
id: 123,
name: "abc",
},
{
id: 1234,
name: "abcd",
},
{
id: 123,
name: "abc",
},
{
id: 4321,
name: 'dcba',
},
];
var key='id';
var indexArray = [];
var newArray = arr.map(a => { if (indexArray.indexOf(a[key]) < 0) { indexArray.push(a[key]); return a; }; return -1; }).filter(a => a != -1);
var indexArray = [];
var newArray = [];
arr.forEach(a => { if (indexArray.indexOf(a[key]) < 0) { indexArray.push(a[key]); newArray.push(a); }});
var newArray = _.uniqBy(arr, key);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Pure JS: map | |
Pure JS: forEach | |
Lodash: uniqBy |
Test name | Executions per second |
---|---|
Pure JS: map | 885628.6 Ops/sec |
Pure JS: forEach | 1108264.6 Ops/sec |
Lodash: uniqBy | 2463656.2 Ops/sec |
Let's break down what's being tested in the provided JSON.
The test is comparing two approaches to remove duplicates from an array using JavaScript:
map()
and filter()
uniqBy()
function from the Lodash libraryPure JavaScript: map
The benchmark definition uses the following code:
var indexArray = [];
var newArray = arr.map(a => {
if (indexArray.indexOf(a[key]) < 0) {
indexArray.push(a[key]);
return a;
}
return -1;
}).filter(a => a != -1);
Here's what's happening:
indexArray
to keep track of unique values.map()
to create a new array, newArray
, with transformed elements.a
in the original array, we check if its value (a[key]
) is already present in indexArray
. If not, we add it to indexArray
and return the original element a
.-1
to indicate that it's a duplicate.Pros:
Cons:
indexOf()
method and the need to iterate over the entire array.uniqBy()
.Lodash: uniqBy
The benchmark definition uses the following code:
var newArray = _.uniqBy(arr, key);
Here's what's happening:
uniqBy()
function.uniqBy()
function takes two arguments: the array to process (arr
) and a function that extracts the unique value from each element (in this case, key
).The uniqBy()
function uses a similar approach as the Pure JavaScript implementation:
Pros:
Cons:
Now, let's look at the benchmark results:
The latest results show that:
Other alternatives to consider:
Set
data structure instead of arrays or objects for storing unique values.filter()
with an initial value of 0 or using reduce()
.Keep in mind that the choice of approach depends on specific use cases and requirements.