Otto
Otto

Reputation: 4190

Order array of objects with TypeScript by value

How can I order this array of objects by object value? I’m using TypeScript.

console.log(this.items);

Output:

(6) [{…}, {…}, {…}, {…}, {…}, {…}]
{id: 3, ref: "P-201721", active: 1, visible: 1, weigth: 0.3, …}
{id: 4, ref: "P-201722", active: 1, visible: 1, weigth: 0.3, …}
{id: 1, ref: "P-201710", active: 1, visible: 1, weigth: 0.5, …}
{id: 2, ref: "P-201711", active: 1, visible: 1, weigth: 0.5, …}
{id: 5, ref: "P-201831", active: 1, visible: 1, weigth: 0.2, …}
{id: 6, ref: "P-201832", active: 1, visible: 1, weigth: 0.2, …}

I tried this, but the array maintains the same order: Sort an array with arrays in it by string

Upvotes: 5

Views: 31680

Answers (2)

arunmmanoharan
arunmmanoharan

Reputation: 2675

You can use Lodash to achieve what you want. You can also use multiple sorting options by passing in the keys in the array inside the sortBy function.

var data = [
{"id": 3, "ref": "P-201721", "active": 1, "visible": 1, "weight": 0.3},
{"id": 4, "ref": "P-201722", "active": 1, "visible": 1, "weight": 0.3},
{"id": 1, "ref": "P-201710", "active": 1, "visible": 1, "weight": 0.5},
{"id": 2, "ref": "P-201711", "active": 1, "visible": 1, "weight": 0.5},
{"id": 5, "ref": "P-201831", "active": 1, "visible": 1, "weight": 0.2},
{"id": 6, "ref": "P-201832", "active": 1, "visible": 1, "weight": 0.2}
]

var sort = _.sortBy(data, ["id","weight"]);

console.log(sort);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

Upvotes: 3

fl0psy
fl0psy

Reputation: 491

Sorting an array of objects can be a little tricky. You have to pass in a custom sorting function to define how you want to compare the objects. How else would .sort() know you want to sort by id? Maybe you want to sort by weight instead.

I've put together an example at https://codepen.io/anon/pen/PEReGE?editors=0012. You can replace the id references with any property if you'd like it sorted by that instead.

items.sort((a, b) => {
  if(a.id > b.id) {
    return 1;
  } else if(a.id < b.id) {
    return -1;
  } else {
    return 0;
  }
});

If you are sorting by a numeric property you can use this shorthand:

items.sort((a, b) => {
  return a.id - b.id;
});

Upvotes: 23

Related Questions