How to sort javascript array following a predetermined hierarchy

Viewed 157

Let's say I have this hierarchy:

0 King
1 Queen
2 Tower
3 Bishop
4 Knight
5 Pawn

and an array with this elements:

array = [Tower, Pawn, Bishop, Queen]

How can I sort it to become like this following the hierarchy?

array = [Queen, Tower, Bishop, Pawn]
2 Answers

Create an object that defines the hierarchies:

const hierarchyMap = {
  King: 0,
  Queen: 1,
  Tower: 2,
  Bishop: 3,
  Knight: 4,
  Pawn: 5,
}

then sort the array based on the hierarchy value:

array.sort((first, second) => hierarchyMap[first] - hierarchyMap[second]);

or vice versa:

array.sort((first, second) => hierarchyMap[second] - hierarchyMap[first]);

const hierarchyMap = {
  King: 0,
  Queen: 1,
  Tower: 2,
  Bishop: 3,
  Knight: 4,
  Pawn: 5,
}


let array = ["Tower", "Pawn", "Bishop", "Queen"];

let sorted = array.sort((first, second) => hierarchyMap[first] - hierarchyMap[second]);

console.log(sorted)

You sort it. Then you map over.

I would suggest to use array with objects. Maybe you want to add more properties later in the future so you can easy add more properties to it.

let data = [
  {pos:5, role:"King"},
  {pos:6, role:"Queen"},
  {pos:4, role:"Tower"},
  {pos:2, role:"Bishop"},
  {pos:3, role:"Knight"},
  {pos:1, role:"Pawn"}
]

let result = data.sort((a,b) => a.pos - b.pos)
             .map(({role}) => role);

console.log(result);

Related