2

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.

Tom Fenech
  • 72,334
  • 12
  • 107
  • 141
Chase Ernst
  • 1,147
  • 1
  • 21
  • 53

3 Answers3

5

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.

LogPi
  • 706
  • 6
  • 11
3

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()

Paolo Moretti
  • 54,162
  • 23
  • 101
  • 92
manji
  • 47,442
  • 5
  • 96
  • 103
1

You don't have to override anything, just pass .sort custom function that will do the sorting:

var rsortby = {
  id     : /^(\d+)/,
  name   : /(\w+)$/,
  status : /-\s*(.+?)\s*-/,
};

var r = rsortby['name'];

[
  '1234 - Active - Workroom',
  '1224 - Active - Breakroom',
  '2365 - Active - Shop',
].
sort(function(a, b) {
  var ma = a.match(r)[1];
  var mb = b.match(r)[1];
  return (ma != mb) ? (ma < mb ? -1 : 1) : 0;
});

// ["1224 - Active - Breakroom", "2365 - Active - Shop", "1234 - Active - Workroom"]
//
public override
  • 974
  • 8
  • 17