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.

1
  • sort with a custom function and a split. Commented May 20, 2014 at 15:31

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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"]
//

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.