0

I've got an array that I want to re order based on the index of an item in the array

I've tried two different methods so far but it seems that the array comes out just as when it was sent in.

function orderPlayers(players, fpIndex){
    for(var i = 0; i < players.length; i ++ ){
        players.move(i, fpIndex);
        fpIndex = fpIndex + 1;
        if(fpIndex > players.length - 1){fpIndex = 0;}
    }
    return players;
 }

 Array.prototype.move = function (from, to) {
     this.splice(to, 0, this.splice(from, 1)[0]);
 };

Example of data:

fpIndex: 1 //The player that is first is at array index 1

Players: {
     player: {
         age: 19,
         name: Bob,
         piece: "red",
         isFirst: false
     }

     player: {
         age: 21,
         name: Steve,
         piece: "blue",
         isFirst: true
     }
}

Should come out as:

Players: {
     player: {
         age: 21,
         name: Steve,
         piece: "blue",
         isFirst: true
     }

     player: {
         age: 19,
         name: Bob,
         piece: "red",
         isFirst: false
     }
}
  • Can you provide some examples with an input and expected output? – abagshaw Aug 29 '17 at 02:28
  • Alright, hope that helps – Simon Chawla Aug 29 '17 at 02:35
  • 1
    Is the idea to just move one element from the specified index to the start of the array? You don't need a loop for that, you can just use one call to `.splice()` to remove it, plus one call to `.unshift()` to insert it. – nnnnnn Aug 29 '17 at 03:59

2 Answers2

0

so you want to reverse an array? have you tried Array.prototype.reverse()?

  • In this case reversing would give the desired result but the player list could be much longer than just two and the first player could be anywhere in the array – Simon Chawla Aug 29 '17 at 12:33
0

Is this what you are looking for? See working example:

var players = 
    {
      "Players": 
      [
        {
          "player": {
            "age": 21,
            "name": "Steve",
            "piece": "blue",
            "isFirst": true
          }
        },

        {
          "player": {
            "age": 19,
            "name": "Bob",
            "piece": "red",
            "isFirst": false
          }
        }
      ]
    }

var fpIndex = 1;

function orderPlayers(plys, index){
  index = index % plys.length;
  if(plys.length === 0 || plys.length === 1 || index === 0){
    return plys;
  }
  let part = plys.splice(plys.length - index);
  return part.concat(plys);
}

console.log(orderPlayers(players.Players, fpIndex));
adda82
  • 165
  • 1
  • 4