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.
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))
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