Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

169
Vistas
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?

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

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

about 4 years ago · Juan Pablo Isaza Denunciar

0

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.

about 4 years ago · Juan Pablo Isaza Denunciar

0

You're not calling the recursive function from outside of the 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;
        }
    }
    
    return recursive(mainArr)
};

Also, I believe the code posted doesn't return the desired output. You can probably do the following:

const array1 = [1,2,4,591,392,391,2,5,10,2,1,1,1,20,20];
array1.sort((a,b) => a-b);

const map = new Map();

array1.forEach((item) => { 
    if(map.has(item)) {
        const storedItem = map.get(item);
        map.set(item, Array.isArray(storedItem) ? [...storedItem, item] : [storedItem, item])
    } else {
        map.set(item, item);
    }
});

console.log(Array.from(map.values()))

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda