2

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.

Teemu
  • 22,058
  • 6
  • 53
  • 101
g5wx
  • 681
  • 1
  • 9
  • 28

3 Answers3

3

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))
vp_arth
  • 13,847
  • 4
  • 37
  • 62
1

You could use the position as index for the new array.

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

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

console.log(order);

Or you could iterate from the end to start, this works for not continuing positions as well.

var mess = [{ lorem: "ipsum", position: 3 }, { lorem: "ipsum", position: 2 }, { lorem: "ipsum", position: 4 }, { lorem: "ipsum", position: 1 }],
    order = [],
    i = mess.length;

while (i--) {
    order.splice(mess[i].position - 1, 0, mess[i]);
}

console.log(order);
Nina Scholz
  • 351,820
  • 24
  • 303
  • 358
1

try sort:

order = mess.sort(function (a, b) {
    return a.position - b.position;
});
Maria
  • 151
  • 2
  • 9