5

I got an array that I want to sort depending on a value on my object.

My array looks like this:

[
  {
   "name": "Ricard Blidstrand",
   "number": "5",
   "position": "b"
  },
  {
   "name": "Gustaf Thorell",
   "number": "12",
   "position": "fw"
  },
  {
   "name": "Rasmus Bengtsson",
   "number": "13",
   "position": "mv"
  }
]

I want to order according to the position-key in this order:

mv > b > fw

Do I need to write it like, or am I wrong?

if(a === "b" && b === "b") {
 return 0;
} else if (a === "b" && b === "mv") {
 return 1;
} 
Sebastian Berglönn
  • 3,920
  • 2
  • 17
  • 33

2 Answers2

16

You need to specify priority array first.

var priority = [ "mv", "b", "fw"];

Now sort your array based on this as

arr.sort( ( a, b ) => priority.indexOf( a.position ) - priority.indexOf( b.position ) );

Demo

var arr = [{
    "name": "Ricard Blidstrand",
    "number": "5",
    "position": "b"
  },
  {
    "name": "Gustaf Thorell",
    "number": "12",
    "position": "fw"
  },
  {
    "name": "Rasmus Bengtsson",
    "number": "13",
    "position": "mv"
  }
];

var priority = [ "mv", "b", "fw"];

arr.sort( ( a, b ) => priority.indexOf( a.position ) - priority.indexOf( b.position ) );

console.log(arr);     
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
3

Create an order object, and assign a value for each position. Sort by taking the order value from the object by the object's position:

var arr = [{"name":"Ricard Blidstrand","number":"5","position":"b"},{"name":"Gustaf Thorell","number":"12","position":"fw"},{"name":"Rasmus Bengtsson","number":"13","position":"mv"}]

var order = { mv: 0, b: 1, fw: 2 }

arr.sort(function(a, b) {
  return order[a.position] - order[b.position]
})

console.log(arr)
Ori Drori
  • 183,571
  • 29
  • 224
  • 209