Imagine that you have an array of fruits and you want to move an element from index = 1
to index = 3
:
javascript// Array of fruits, you'll move the apple before the watermelon let fruits = ['Grape', 'Apple', 'Kiwi', 'Mango', 'Watermelon']; let moveElem = ((from, to, arr) => { // Deletes the element from old position let [elem] = arr.splice(from, 1); // Inserts the element into new position arr.splice(to, 0, elem); })(1, 3, fruits); console.log(fruits); // ["Grape", "Kiwi", "Mango", "Apple", "Watermelon"]
Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.