How to place an element in an array from one place to another?

Posted on

Answer

Consider the table ['one', 'two', 'four', 'three'] and we want to organize the last two elements.


/**
 * move element one place to other in existing array
 * @param {any[]} arr: array Value
 * @param {number} from: index of value that need to be moved
 * @param {number} to: index where need to be placed
 */
export const shiftInsert = (arr: any[], from: number, to: number) => {
  const cutOut = arr.splice(from, 1)[0]; // cut the element at index 'from'
  arr.splice(to, 0, cutOut);            // insert it at index 'to'
};

Example


const data = ['one', 'two', 'four', 'three'];
shiftAndInsert(data, 3, 2);
console.log(data);
// output: ['one', 'two', 'three', 'four']

Leave a Reply

Your email address will not be published.