2

I have an array which looks like this:

  serials = [ serial : 8H51495999, material : 17, status: 01
              serial : 8H51495143, material : 17, status: 01
              serial : 8Z51495143, material : 17, status: 01 ]

I need to sort it by serial, so order would be

              serial : 8H51495143, material : 17, status: 01
              serial : 8H51495999, material : 17, status: 01
              serial : 8Z51495143, material : 17, status: 01

How can I achieve that? Thank you, Tim

Tim
  • 71
  • 4
  • 13

2 Answers2

2

Let's try Array.prototype.sort() in JS

serials.sort(function(a, b) {
      if (a.serial < b.serial) {
        return -1;
      }
      if (a.serial > b.) {
        return 1;
      }
      // a must be equal to b
      return 0;
    });
taile
  • 2,738
  • 17
  • 29
1

Assuming, you have an array of objects and the values are strings, then you could use String#localeCompare for the sorting callback with Array#sort.

var serials = [{ serial : '8H51495999', material : '17', status: '01' }, { serial : '8H51495143', material : '17', status: '01' }, { serial : '8Z51495143', material : '17', status: '01' }];

serials.sort(function (a, b) {
    return a.serial.localeCompare(b.serial);
});

console.log(serials);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392