I'm sure this is super simple, and I don't really want a complete solution, but pointing in the right direction as I'm learning.
I have:
let randomArray = [1,2,4,591,392,391,2,5,10,2,1,1,1,20,20];
and the goal is to make it look like this, grouping like items:
[[1,1,1,1],[2,2,2],[10],[20,20],[391],[392],[591]]
My following code arranges, and groups fine. I push the temp to my Group array. But when I reset my "tempArray" to make it empty ready for the next "group", it removes the data from my group as well. Because it's linked? I assume? Maybe?
The only thing left at the end is the last item.
How do I stop it doing this?
// My SOlution
let randomArray = [1,2,4,591,392,391,2,5,10,2,1,1,1,20,20];
let tempArray = [];
let groupArray = [];
function cleanTheRoom (arr) {
let ascendingArray = arr.sort(function(a,b) {
return a - b;
});
tempArray.push(randomArray[0])
for (let i = 1; i <= randomArray.length; i++) {
if (randomArray[i] === tempArray[0]) {
tempArray.push(randomArray[i])
} else {
groupArray.push(tempArray);
tempArray = []
tempArray.push(randomArray[i])
}
} console.log(groupArray)
}
cleanTheRoom(randomArray);
tempArray.length = 0
which should becometempArray = []
. Simple as that. You should assign a new array totempArray
, otherwise all thetempArray
references will need to keep a reference to the original values, which is why you get the strange logs. There are faster (and easier) ways to do that, though. – ModenagroupArray.push([...tempArray])
. That would do the job as well as long as your array only holds primitives. This does the job because it pushes the array primitive values to the groupArray, which won't be linked to thetempArray
anymore. Either way, it should work as intended. – Modenatemp
array in thegroupArray
array in the last iteration of the loop otherwise thegroupArray
won't contain the last number, i.e.591
– NadorgroupArray.push([...tempArray])
doesn't appear to work in the same way, it just lists them. I may be doing something wrong though. I have noticed that the last item did not push, and I will do exactly that, thank you. – Ungodly