I need sort array by name
['b','a' ,'c' ,'e' ,'d' , .....]
but I want 'c' push to start in resurt array !
['c','a' , 'b' , 'd' ,'e' , ....]
How can I do it this?
function sortByKey(array, key) {
return array.sort(function (a, b) {
var x = a[key];
var y = b[key];
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
});
Yes I can delete 'c' from array and add him in final result but I search best case
You can create a another array that will allow you to configure priority elements and then you can compare values in custom sort function.
Note: not sure about Fast but this will allow you to sort and make few configurations for priority elements
var data = ['b', 'a', 'c', 'e', 'd']
var priority = ['c'];
function getPriority(item) {
var max_value = 9999999999;
var index = priority.indexOf(item);
return index === -1 ? max_value : index
}
data.sort(function(a, b) {
if ([a, b].some(function(x) {
return priority.indexOf(x) > -1
})) {
return getPriority(a) - getPriority(b);
} else {
return a.localeCompare(b);
}
});
console.log(data)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With