0

I have an array of objects like:

const arr = [
  {
    name: 'John',
    age: 20,
  },
  {
    name: 'Mark',
    age: 30,
  },
  ...
]

And I have a service invocation which has an order parameter which is an object with two properties: a field which is the field I want to sort my array of object by and an 'asc' which is a Boolean value for do I want the list in ascending or descending order.

const order = {
   field: 'name',
   asc: true,
}

I would have started something like this but it does not seem to be the solution

    orderedList = list.sort((a, b) => {
      if (order.asc) {
        return a[order.field] - b[order.field];
      } else {
        return b[order.field] - a[order.field];
      }
    });
Laterneman
  • 267
  • 2
  • 15
  • 1
    the subtraction trick only works for numbers (for `age`) but for strings etc., you have to use `>`, `<` or compare by other means. – Ramesh Reddy Sep 02 '21 at 07:41
  • 1
    This may help: https://stackoverflow.com/a/1129270/2358409 – uminder Sep 02 '21 at 07:42
  • Yes I've seen that, however I struggled to implement my 'asc' property into a compare function for some reason - I feel numb this morning, sorry for the dumb question. Initially I tried like this: ``` orderedList= list.sort((a, b) => { if (order.asc) { return a[order.field] > b[order.field] ? 1 : 0; } else { return a[order.field] < b[order.field] ? -1 : 0; } }); ``` – Laterneman Sep 02 '21 at 07:45
  • Does this answer your question? [Sort array of objects by string property value](https://stackoverflow.com/questions/1129216/sort-array-of-objects-by-string-property-value) – malarres Sep 02 '21 at 08:20
  • I think I fixed it, now it works. Thank you all! – Laterneman Sep 02 '21 at 08:23

2 Answers2

2

If you want to sort by string in alphabetical order, you can so something like this:

const arr = [{
    name: 'John',
    age: 20,
  },
  {
    name: 'Mark',
    age: 30,
  },
  {
    name: 'Luke',
    age: 19
  }
]
const order = {
  field: 'name',
  asc: true,
}

orderedList = arr.sort((a, b) => {
  if (order.asc) {
    if (a[order.field] > b[order.field]) {
      return 1
    } else if (a[order.field] < b[order.field]) {
      return -1
    } else {
      return 0
    }
  }
});
console.log(orderedList)
J_K
  • 688
  • 5
  • 12
2

You can write the comparator function like so:

arr.sort((a, b) => {
    var ret;
    // assume ascending order and set return value to -1/0/1
    if (a[order.field] < b[order.field]) {
        ret = -1;
    } else if (a[order.field] > b[order.field]) {
        ret = 1;
    } else {
        ret = 0;
    }
    // for descending order simply invert the sign
    return order.asc ? ret : -ret;
});
// note that arr is sorted in-place
Salman A
  • 262,204
  • 82
  • 430
  • 521