2017-08-29 77 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));