2017-08-29 111 views
0

,數組出來我已經得到了我想要基於重新排序JavaScript數組

我已經試過兩種不同的方法,到目前爲止項目的數組中的索引重新秩序,但它似乎一個數組只是當它在發送數據的

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]); 
}; 

例:

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

應該站出來爲:

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

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

可以爲用戶提供的輸入和預期輸出的例子嗎? – abagshaw

+0

好的,希望對你有所幫助 –

+1

是否只是將一個元素從指定的索引移動到數組的開頭?您不需要循環,只需使用一次調用'.splice()'將其刪除,再加上一次調用'.unshift()'來插入它。 – nnnnnn

回答

0

所以你想反轉一個數組?你有沒有試過Array.prototype.reverse()

+0

在這種情況下,反轉會得到期望的結果,但玩家名單可能比僅兩名長得多,並且第一名玩家可能在陣列中的任何位置 –

0

這是你在找什麼?見工作示例:

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