求一个JS数组重新排序的算法

 $scope.testArr = [
     {id:"1",name:"yi"},
     {id:"2",name:"er"},
     {id:"3",name:"san"},
     {id:"4",name:"si"}
    ]

 <div class="list">
     <div ng-repeat="item in testArr" ng-click="foward(item)">{{item.name}}</div>
  </div>

问题:根据首次点击选中的项 重新生成数组 当前选中的项为数组的第一个元素,依次类推
例如首次点击的是id为2的项 则新数组为:
[{id:"2",name:"er"},{id:"3",name:"san"}, {id:"4",name:"si"}, {id:"1",name:"yi"}]
首次选中的是id为3的项 新数组为
[{id:"3",name:"san"}, {id:"4",name:"si"},{id:"1",name:"yi"}{id:"2",name:"er"}]


小怪兽爱吃肉
浏览 950回答 1
1回答

温温酱

function&nbsp;reSort(arr,index){ &nbsp;&nbsp;&nbsp;&nbsp;index&nbsp;=&nbsp;index&nbsp;||&nbsp;0;&nbsp;&nbsp;&nbsp;&nbsp;if(&nbsp;!arr&nbsp;||&nbsp;arr.length&nbsp;===&nbsp;0&nbsp;||&nbsp;index&nbsp;>&nbsp;arr.length&nbsp;)&nbsp;return&nbsp;arr;&nbsp;&nbsp;&nbsp;&nbsp;var&nbsp;front&nbsp;=&nbsp;arr.slice(0,index);&nbsp;&nbsp;&nbsp;&nbsp;var&nbsp;end&nbsp;=&nbsp;arr.slice(index);&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;end.concat(front); }var&nbsp;arr&nbsp;=&nbsp;&nbsp;[ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{id:"1",name:"yi"}, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{id:"2",name:"er"}, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{id:"3",name:"san"}, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{id:"4",name:"si"} &nbsp;&nbsp;&nbsp;&nbsp;]; reSort(arr,1);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript