Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - loop thro array and sort the objects based on the key value inside [duplicate]

I have a simple array which i get via json where each object has a position key with a certain value. I would like to reorder them (change their index) based on the value of that key inside.

Here is what i have so far: JSFiddle

The code:

var mess = [
    a = {
    lorem: "ipsum",
    position: 3
  },
  b = {
    lorem: "ipsum",
    position: 2
  },
  c = {
    lorem: "ipsum",
    position: 4
  },
  d = {
    lorem: "ipsum",
    position: 1
  }
]

var order = [];

for (i = 0; i < mess.length; i++) {
    order.splice(mess[i].position - 1, 0, mess[i]);
}

The issue with the current loop is that only the first and last object get arranged properly (1, 4) within order array.

like image 508
g5wx Avatar asked Nov 01 '25 03:11

g5wx


1 Answers

You can use Array.prototype.sort method:

let mess = [
	{lorem: "ipsum",position: 3},
	{lorem: "ipsum",position: 2},
	{lorem: "ipsum",position: 4},
	{lorem: "ipsum",position: 1}
];

// 
console.log(mess.sort((a, b) => a.position - b.position))
like image 152
vp_arth Avatar answered Nov 02 '25 19:11

vp_arth