Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting an array alphabetically, but with exceptions

I have the following array structure

[{
  name: "Mobile Uploads"
}, {
  name: "Profile Pictures"
}, {
  name: "Reports"
}, {
  name: "Instagram Photos"
}, {
  name: "Facebook"
}, {
  name: "My Account"
}, {
  name: "Twitter"
}]

I want to reorder the array so that its in the following order: Profile Pictures, Mobile Uploads, Instagram Photos, and the objects afterwards are in alpabetical order.

like image 221
Brown PO Avatar asked Feb 07 '23 13:02

Brown PO


1 Answers

What you want to do is to make an object that holds the sort exceptions. Then you can write a custom sort() function that accounts for your exceptions.

var list = [{
  name: "Date"
}, {
  name: "Mobile Uploads"
}, {
  name: "Profile Pictures"
}, {
  name: "Fig"
}, {
  name: "Instagram Photos"
}, {
  name: "Cherry"
}, {
  name: "Apple"
}, {
  name: "Banana"
}];

var exceptions = {
  "Profile Pictures": 1,
  "Mobile Uploads": 2,
  "Instagram Photos": 3
}

list.sort(function(a, b) {
  if (exceptions[a.name] && exceptions[b.name]) {
    //if both items are exceptions
    return exceptions[a.name] - exceptions[b.name];
  } else if (exceptions[a.name]) {
    //only `a` is in exceptions, sort it to front
    return -1;
  } else if (exceptions[b.name]) {
    //only `b` is in exceptions, sort it to back
    return 1;
  } else {
    //no exceptions to account for, return alphabetic sort
    return a.name.localeCompare(b.name);
  }
});

console.log(list);
like image 194
Dave Avatar answered Feb 09 '23 02:02

Dave