This next example function works just fine:
const data = [1, 2, 3, 4, 5];
function insertAndShift(arr, number) {
const cutOut = arr.splice(-number);
return [...cutOut, ...arr];
}
console.log('Output: ', insertAndShift(data, 2));
// Output: [4,5,1,2,3]
However, when I call the function another time, I suddenly get a wrong response:
const data = [1, 2, 3, 4, 5];
function insertAndShift(arr, number) {
// The next starting array should be [1,2,3,4,5] on both occasions.
// However, on the second occasion it will only be [1,2,3].
// Which was the array in the first time the function was called.
console.log('arr: ', arr);
const cutOut = arr.splice(-number);
return [...cutOut, ...arr];
}
console.log('Output: ', insertAndShift(data, 2));
// Output: [4,5,1,2,3]
console.log('Output: ', insertAndShift(data, 3));
// Output: [1,2,3]
// Should be: [3,4,5,1,2]
Is this a scoping issue? Or what is exactly happening here?
splicemutates the array. So after your first calldatahas changed.