-3

My array is:

var array = ["author", "1", "2", "3", "5", "6"]

I am trying to move author on first position and than second position and end of the array, on click of button.

DjaouadNM
  • 22,013
  • 4
  • 33
  • 55

2 Answers2

1

You could take a closure over the index to swap with the next and check if the swapping is possible. If not return the array, otherwise swap the elements.

const
    swap = (a, i = 0) => () => {
        if (i + 1 >= a.length) return a;
        [a[i + 1], a[i]] = [a[i], a[i +  1]];
        i++;
        return a;
    };

var array = ["author", "1", "2", "3", "5", "6"],
    s = swap(array);

console.log(...array);
console.log(...s());
console.log(...s());
console.log(...s());
console.log(...s());
console.log(...s());
console.log(...s());
If you do not like the destructuring and assigning the values, you could use splice instead, which spreads an spliced array from the following index with a length of one item.

const
    swap = (a, i = 0) => () => {
        a.splice(i, 0, ...a.splice(++i, 1));
        return a;
    };

var array = ["author", "1", "2", "3", "5", "6"],
    s = swap(array);

console.log(...array);
console.log(...s());
console.log(...s());
console.log(...s());
console.log(...s());
console.log(...s());
console.log(...s());
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

On click of the button get the indexOf author & in another variable get the element at the next index. If the next position in the array is not undefined interchange the position of author with immediately next element

var array = ["author", "1", "2", "3", "5", "6"]


function shiftAuthor() {
  // get index of author in the array
  let currPosition = array.indexOf('author');
  // if the index of author +1 is not undefined
  if (array[currPosition + 1] !== undefined) {
    // get the element at the next index of author
    let elemAtNextPos = array[currPosition + 1];
    // interchange their position
    array[currPosition + 1] = 'author'
    array[currPosition] = elemAtNextPos;
  }
  console.log(array)
}
<button type='button' onclick='shiftAuthor()'> Shift Author </button>
brk
  • 48,835
  • 10
  • 56
  • 78