4

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.

4
  • please add data and the code, you tried to the question. please have a look here, too: minimal reproducible example Commented Jan 18, 2017 at 8:31
  • Fiddle is posted. Commented Jan 18, 2017 at 8:32
  • What all of these global a, b, c, d variables for? Commented Jan 18, 2017 at 8:47
  • Just for a quick demo in fiddle. Commented Jan 18, 2017 at 8:56

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

4 Comments

Yep, forgot about sort, thanks!
Or mess.sort(function(a, b) { return a.position - b.position }) if you run in an enviroment that doesn't have arrow functions.
@Ben, you miss return statement
@vp_arth, saw that after posting. Fixed :)
1

try sort:

order = mess.sort(function (a, b) {
    return a.position - b.position;
});

1 Comment

Thanks Maria, forgot about sort - voted up!
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);

1 Comment

Thanks Nina, works great!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.