[英]Move a group of items from the array a specified number of positions
我想要執行以下操作的javascript算法:
示例:我有以下數組:
條目:[1,2,3,4,5,6,7]
我希望選定的項(2,3,6)在數組中每個下降一個位置。
預期輸出:[2,3,1,4,6,5,7]
如何對所選項目進行分組處理的算法。
我嘗試使用JavaScript算法將每個項目更新到索引-1位置,但不適用於組處理。
Array.prototype.move = function (old_index, new_index) {
if (new_index >= this.length) {
var k = new_index - this.length;
while ((k--) + 1) {
this.push(undefined);
}
}
this.splice(new_index, 0, this.splice(old_index, 1)[0]);
return this; // for testing purposes
};
我就是這樣
function ascend(values, by, source) { move.map(function(value) { old_index = source.indexOf(value); source.splice(old_index - by, 0, source.splice(old_index, 1)[0]); }); return source; } source = [1,2,3,4,5,6,7]; move = [2,3,6]; result = ascend(move, 1, source); console.log(result);
var arr=[2, 3, 1, 4, 5, 6, 7]
Array.prototype.descendElementIndex=function(element){
var _this=this;
if(Array.isArray(element)){
element.forEach(function(e){
_this.descendElementIndex(e);
});
}
var pos=this.indexOf(element);
if(pos<=0){return};
this[pos]=this[pos-1];
this[pos-1]=element;
}
[1,4,6].forEach(function(e){
arr.descendElementIndex(e);
});
console.log(arr);//[2, 1, 4, 3, 6, 5, 7]
Call the descendElementIndex for selected elements in your widget like above sample array([1,4,6])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.