'Recursive function on sorted array returns undefined

I'm attempting to solve 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], make a function that organizes these into individual array that is 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
};

Idea is to go through the array that I've sorted, filter using the first item in the array to get back a new array (single value if there's only one) with the like items, push it to my accumulator and then delete every instance of it in the original array.

I'm trying to do this recursively until there are no items left in the original array but it's returning undefined.

Any ideas where I'm going wrong?



Solution 1:[1]

inside your recursive function you are doing return recursive(mainArr); instead try to return recursive(arr);

Solution 2:[2]

You never call the function recursive.

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;
        }
    }
    
    recursive(mainArr) //<--- Call it!
};

You will also notice that sortArray does not return anything, so you may want to change recursive(mainArr) to return recursive(mainArr) to get a return.

Of note, the code does not produce the desired result, but this fix should get you going.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Diesel