Moving an item inside an array in Javascript

Hi all

why was it necessary to add [0] in const element = output.splice(index, 1)[0]; to create this function to move an item inside an array? thanks

const numbers = [1, 2, 3, 4];

function move(array, index, offset) {
    const output = [...array];
    const element = output.splice(index, 1)[0];
    output.splice(position, 0, element);
    return output;
}

const output = move(numbers, 0, -1);

console.log(output);

What is position? It doesn’t seem to be declared anywhere?

To answer your question: splice() returns an array of the removed elements (Array.prototype.splice() - JavaScript | MDN). You are passing 1 as the deleteCount to splice() so you will get an array with one deleted element in it. It’s at position 0 of the array so to access it you use [0].

1 Like

My code was incomplet…position is a const position = index + offset;
A bit confusing when things starts getting nested but your explanation helps a bit. Thank you!