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;
} 
                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);     
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With