Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fast sorting array by name without one

Tags:

javascript

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

like image 874
zloctb Avatar asked Feb 04 '26 07:02

zloctb


1 Answers

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)
like image 62
Rajesh Avatar answered Feb 05 '26 21:02

Rajesh