<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
var test = [{"value":"97535676-acbb-41f4-b8ea-91e8e5e3fc0d","label":"Overview"},{"value":"f1e5845d-b5a4-4725-9813-f601eaed6826","label":"test 1"},{"value":"056d7e5a-b947-4c10-8b38-13416deebe4a","label":"Announcements"},{"value":"18149d83-8191-4c60-afca-d976f6f63ca5","label":"Browse buttons"},{"value":"20b145fa-14ae-457c-9fec-04fdd48ddba2","label":"ztest"},{"value":"00142552-9bf6-49a8-829d-152d8448ac5f","label":"Watson News"},{"value":"578695c6-4e4c-4c8d-ba8a-2ede7b6abd19","label":"Filtered"},{"value":"6b6fef15-a13e-423b-875d-7700737dccf4","label":"Curated"}]
_.sortBy(test, [
name => {
const priority = ['overview'];
if (_.includes(priority, name)) {
return _.indexOf(priority, name);
} else {
return name.length;
}
},
name => name,
]);
test.sort(function(a, b) {
const valueA = a.label.toUpperCase();
const valueB = b.label.toUpperCase();
if (valueB === 'OVERVIEW') {
return 1;
} else if (valueA === 'OVERVIEW') {
return -1;
}
return valueA < valueB ? -1 : valueA > valueB ? 1 : 0;
});
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
lowdash | |
JS |
Test name | Executions per second |
---|---|
lowdash | 85012.2 Ops/sec |
JS | 590956.7 Ops/sec |
This benchmark compares two approaches to sorting an array of objects:
Option 1: Using Lodash's _.sortBy()
function.
_.sortBy()
function with a custom comparison function. This function prioritizes objects with the label "Overview" at the beginning of the sorted array, then sorts remaining objects by their label length. Option 2: Native JavaScript sort()
method.
sort()
method. It prioritizes objects with the label "Overview" at the beginning, then sorts the remaining objects alphabetically by their label._.sortBy()
.Other Considerations:
JS
test) is significantly faster (around 7 times faster) than using Lodash's _.sortBy()
function (lowdash
test). This suggests that in this specific case, the overhead of using Lodash might outweigh its benefits._.sortBy()
might be considered slightly more concise for simple sorting tasks.Alternatives:
In addition to these two options, there are other libraries and methods you could explore for sorting arrays in JavaScript:
sort()
can provide more flexibility depending on your specific needs.