2

I have an array containing objects which have a name and type.

I am trying to always sort the array so the objects are sorted by type as home , draw, away.

An example of one of the arrays looks like this. The arrays are sent from a backend and are sent in different orders each time. The names are also different each time.

var arr = [
  {
    type: 'home',
    name: 'Liverpool Blues'

  }, {
    type: 'away',
    name: 'Manchester Reds'
  },
  {
    type: 'draw',
    name: 'Draw'
  }
];

My code looks like this. I thought that draw should get sorted to the middle if home is always pushed to the front, and away is always pushed to the end, although I think there must be an error with how I am sorting the array.

return [...selections].sort((a, b) => {
    if (a.type === "HOME") return -1;
    if (b.type === "AWAY") return 1;
    return 0;
});

3 Answers3

1

You could use an object, which groupes the type property by the wanted order.

var array = [{ type: 'home', name: 'Liverpool Blues' }, { type: 'away', name: 'Manchester Reds' }, { type: 'draw', name: 'Draw' }],
    order = { home: 1, draw: 2, away: 3 };

array.sort(function (a, b) { return order[a.type] - order[b.type]; });

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

You could simply iterate and position them directly:

let arr = [];
selections.forEach(s => {
    if (s.type === "HOME") arr[0] = s;
    if (s.type === "DRAW") arr[1] = s;
    if (s.type === "AWAY") arr[2] = s;
})

Then arr will be on the correct order.

altschuler
  • 3,694
  • 2
  • 28
  • 55
0

The order you want is reverse alphabetical (home, draw, away), so reverse sorting on the type property will do:

var arr = [
  {
    type: 'home',
    name: 'Liverpool Blues'

  }, {
    type: 'away',
    name: 'Manchester Reds'
  },
  {
    type: 'draw',
    name: 'Draw'
  }
];

arr.sort((a, b) => b.type.localeCompare(a.type));

console.log(arr);
Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156