Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript .sort override

I have an array of strings, which are all similar except for parts of them, eg:

["1234 - Active - Workroom", 
 "1224 - Active - Breakroom",
 "2365 - Active - Shop"]

I have figured out that to sort by the ID number I just use the JavaScript function .sort(), but I cannot figure out how to sort the strings by the area (eg: "Workroom etc..").

What I am trying to get is:

["1224 - Active - Breakroom", 
 "2365 - Active - Shop", 
 "1234 - Active - Workroom"]

The "Active" part will always be the same.

From what I have found online, I have to make a .sort() override method to sort it, but I cannot figure out what I need to change inside the override method.

like image 301
Chase Ernst Avatar asked Dec 19 '25 14:12

Chase Ernst


2 Answers

Example for you

var items = [
  { name: "Edward", value: 21 },
  { name: "Sharpe", value: 37 },
  { name: "And", value: 45 },
  { name: "The", value: -12 },
  { name: "Magnetic" },
  { name: "Zeros", value: 37 }
];
items.sort(function (a, b) {
    if (a.name > b.name)
      return 1;
    if (a.name < b.name)
      return -1;
    // a must be equal to b
    return 0;
});

You can make 1 object to describe your data . Example

data1 = { id : 12123, status:"Active", name:"Shop"}

You can implement your logic in sort(). 
Return 1 if a > b ; 
Return -1 if a < b 
Return 0 a == b. 

Array will automatically order follow the return Hope it'll help.

like image 124
LogPi Avatar answered Dec 21 '25 02:12

LogPi


You can give the sort method a function that compares two items and returns the order:

yourArray.sort(function(item1, item2){
    // compares item1 & item2 and returns:
    //  -1 if item1 is less than item2
    //  0  if equal
    //  +1 if item1 is greater than item2
});

Example in your case :

yourArray.sort(function(item1, item2){
    // don't forget to check for null/undefined values
    var split1 = item1.split(' - ');
    var split2 = item2.split(' - ');
    return split1[2] < split2[2] ? -1 : (split1[2] > split2[2] ? 1 : 0);
});

see Array.prototype.sort()

like image 42
manji Avatar answered Dec 21 '25 03:12

manji



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!