0

I would like some algorithm in javascript that does the following operation:

example: I have the following array:

Entry: [1,2,3,4,5,6,7]

enter image description here

I want the selected items (2,3,6) to descend one position each in the array.

Expected output: [2,3,1,4,6,5,7]

enter image description here

How to do this algorithm for group handling of selected items.

I tried using a javascript algorithm that updates every item to the index -1 position but it does not work for group handling.

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
};
  • 2
    Can you edit your question to include a [mcve] of your attempts so far? – evolutionxbox May 10 '17 at 13:45
  • The code you mentioned is just a copy paste from another answer: http://stackoverflow.com/questions/5306680/move-an-array-element-from-one-array-position-to-another you need to modify it for your use – rishipuri May 10 '17 at 14:00

2 Answers2

0

This is how i would do,

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);
rishipuri
  • 1,498
  • 11
  • 18
0
    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])
Chand Ra
  • 69
  • 6