Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom sort array to order object based on string - Javascript [duplicate]

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;
} 
like image 922
Sebastian Berglönn Avatar asked Jan 30 '18 09:01

Sebastian Berglönn


2 Answers

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);     
like image 117
gurvinder372 Avatar answered Nov 19 '22 23:11

gurvinder372


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)
like image 32
Ori Drori Avatar answered Nov 19 '22 23:11

Ori Drori