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

2 Answers 2

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;
    });
Sign up to request clarification or add additional context in comments.

Comments

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

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.