My current task involves solving this problem recursively:
Clean the room function: given an input of [1,2,4,591,392,391,2,5,10,2,1,1,1,20,20], create a function that organizes these into individual arrays that are ordered. For example, answer(ArrayFromAbove) should return: [[1,1,1,1],[2,2,2], 4,5,10,[20,20], 391, 392,591]
Array:
const array1 = [1,2,4,591,392,391,2,5,10,2,1,1,1,20,20];
array1.sort((a,b) => a-b);
Main Function:
const sortArray = (mainArr) => {
let acc = [];
console.log(acc, "acc");
const recursive = (arr) => {
if (arr.length > 1) {
console.log("inside func2 ", acc);
let likeArr = singArr(arr, arr[0]);
console.log(likeArr, "like");
arr = deleteVal(arr, arr[0]);
acc.push(likeArr);
return recursive(mainArr);
}
else {
return acc;
}
}
};
Helper Functions:
const singArr = (arr1, val) => {
let returnVal = arr1.filter(num => num === val);
return (returnVal.length === 1 ? returnVal[0] : returnVal);
};
const deleteVal = (arr, val) => {
let returnVal = arr.filter(num => num !== val);
return returnVal
};
The concept is to iterate through the sorted array, filter using the first item in the array to get back a new array (containing just one value if there's only one match), push it to the accumulator, and then remove every instance of it from the original array.
I'm attempting to achieve this recursively until all items have been processed, but I'm getting undefined as the result.
Any insights on where my mistake might be?