Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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)
      return1;
    if (a.name < b.name)
      return -1;
    // a must be equal to breturn0;
});

You can make 1 object to describe your data . Example

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

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

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

Solution 2:

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 valuesvar split1 = item1.split(' - ');
    var split2 = item2.split(' - ');
    return split1[2] < split2[2] ? -1 : (split1[2] > split2[2] ? 1 : 0);
});

see Array.prototype.sort()

Solution 3:

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

Post a Comment for "Javascript .sort Override"