When you call a function like this:
removeElementByIndex(4, origionalArray);
"origionalArray" is passed as an argument to the parameter "arr" in the function. This means that within the function, "arr" refers to the same array object as "origionalArray".
In JavaScript, arrays are passed by reference. This means that both "arr" and "origionalArray" point to the same memory location where the array data is stored.
Therefore, if you modify "arr" inside the function by doing this:
arr.splice(0, arr.length);
you are directly modifying "origionalArray".
If you were to do something like:
arr = [...tmpArr];
this line does not change "origionalArray"; instead, it reassigns "arr" to a new array created from "tmpArr". After this line, "arr" no longer points to "origionalArray"; it now points to a new array, so "origionalArray" is unaffected.
If you want "origionalArray" to be populated, do this:
const origionalArray = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
const removeElementByIndex = function(ind, arr) {
let j = 0, tmpArr = [];
for (let i=0; i<arr.length; i++) {
if (i !== ind) {
tmpArr[j] = arr[i];
j++;
};
};
arr.splice(0, arr.length);
console.log(origionalArray, arr, tmpArr);
arr.push(...tmpArr);
console.log(origionalArray, arr, tmpArr);
};
removeElementByIndex(4, origionalArray);
or this:
const origionalArray = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
const removeElementByIndex = function(ind, arr) {
let j = 0, tmpArr = [];
for (let i=0; i<arr.length; i++) {
if (i !== ind) {
tmpArr[j] = arr[i];
j++;
};
};
arr.splice(0, arr.length);
console.log(origionalArray, arr, tmpArr);
for(let i=0; i<tmpArr.length; i++){
arr.push(tmpArr[i]);
}
console.log(origionalArray, arr, tmpArr);
};
removeElementByIndex(4, origionalArray);
Guys! To learn more about arrays, please click the link below to watch me solve HackerRank's "Arrays - DS" online coding challenge with detailed explanations, on my YouTube channel.
I smashed HackerRank's "Arrays - DS" Online Coding Challenge!