Within a small coding project I recently completed, I handled an array consisting of 3 subarrays, with each subarray containing 4 objects. I passed this array through a function that gradually removes values from each subarray until only 1 object remains in each one. Ultimately, the function returns an object holding the last remaining 3 objects.
However, an issue arises as the original array is being altered during this process, regardless of my attempts to prevent it. I tested various methods, such as:
var itemsArr = [[obj1, obj2, obj3, obj4], [moreObj1, moreObj2, moreObj3, moreObj4],[lastObj1, lastObj2, lastObj3, lastObj4]];
// each item in itemsArr subarrays represents objects with name, url, and id keys.
var generateResults = function(array, num){
var arr = array.slice(); // creating a copy of the original array here (though it's not functioning as expected)
// have also attempted arr = [].concat(array);
var counter = 1;
var holderObj;
var results = {
baby: null,
husband: null,
home: null
};
var tempArr;
// iterate over the outer array, which contains arrays within each element
var i = 0;
while (true){
if (arr[i].length === 1){
holderObj = arr.splice(i,1)[0][0];
i--; // adjusting for the reindexing of arr. alternatively, can iterate backwards if needed
results[holderObj.id] = holderObj;
}
if (arr[i]){
for (var j=0; j<arr[i].length; j++){
if (counter === num){
arr[i].splice(j,1);
counter = 0;
j--; // accommodating the reindexing of arr[i]. Could also iterate in reverse
}
else{
counter ++;
}
}
}
if (results.baby !== null && results.husband !== null && results.home !== null){
break;
}
else if (i === arr.length-1){
i = -1;
}
i++;
}
return results;
}
How can I prevent the original itemsArr from undergoing modifications when calling generateResults(itemsArr, num)?
I've also experimented with replacing the initial line of generateResults with var arr = [].concat(array);