Error message: The recursive function is unable to return a value when operating

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?

Answer №1

When working within your recursive function, make sure to return the recursive call with the correct array parameter. Instead of using mainArr, try using arr.

Answer №2

The recursive function is not being called from outside of the 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;
        }
    }
    
    return recursive(mainArr)
};

It seems that the provided code may not give the expected output. Consider the following alternative approach:

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()))

Answer №3

The function recursive is never called in this code snippet.

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;
        }
    }
    
    // You need to actually call the recursive function here
    recursive(mainArr);
};

It should be noted that the sortArray function does not have a return statement. To fix this, change recursive(mainArr) to return recursive(mainArr) to ensure you get a return value.

Although the code as it stands does not provide the expected outcome, making these adjustments should help move you in the right direction.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Challenges with fetching data from APIs in NextJs

I am currently working on a basic NextJs TypeScript application with the app router. The following code is functioning correctly: export default async function Page() { const res = await fetch("https://api.github.com/repos/vercel/next.js"); ...

Fill the angular ui-bootstrap popover with content

Can anyone help me with populating an angular ui bootstrap popover? My goal is to populate the popover with a collection of actor names. Below is the code snippet: <div class="container" ng-if="radioModel=='Search for Actor'"> <p> ...

What is the best way to display an alert when the button is clicked repeatedly?

Is it possible to keep displaying the alert every time we click the button, rather than just once after clicking it? I currently have an alert set to trigger when a button is clicked, but it disappears after 3 seconds. How can I make it show up again with ...

What is the best way to include JSX in a separate HTML file?

Currently developing a PWA using create-react-app. Upon inspecting the index.html page, I realized there are no links to any JS files, leading me to assume that CRA injects JSX into the 'root' div of index.html. Now, my goal is to include an offl ...

Determine distinct items in an array that match a predefined criteria

I have a list of objects with two keys, img1 and img2. I need to identify unique objects based on the values of img1, while also retaining the corresponding value of img2. This is the current code I am using: const imgs_arr = [ ...new Set( inpu ...

Get a PDF file from MongoDB via jade Template Engine

Currently, I am utilizing Node, along with express, Jade, and a MongoDB to query the database and showcase the data on a webpage. Within the database, PDFs are stored and my goal is to enable users to download these files directly from the webpage. While ...

Search form with a variety of fields that allows for searching without needing to repeat the component for each condition

I am currently facing an issue with my form that consists of multiple fields, each used to search through an API and display matching data in a table below. While I have successfully implemented this for one field, I now need it to work for all fields with ...

MANDATORY activation of CONFIRMATION

Hello everyone, I'm seeking assistance with my code. Below is the form code I need help with: <form action="input.php" method="POST"> <input type="text" class="input" name="firstname" placeholder="First Name" required> <input t ...

The Chrome browser allows interaction between two separate divs, where a button located in one div can impact

One issue I encountered involves a button located within a div that has unintended consequences for another div. Here is the basic structure of the elements: <div> <div> <div> <div> <butto ...

The problem with THREE JS OcclusionComposer: encountering "Cannot read properties of undefined (reading 'x')" error

I am attempting to replicate the Volumetric Lighting demonstration created by JMSWRNR but I am encountering difficulties with the Occlusion Composer. Since I am not well-versed in GLSL, debugging has proven to be quite challenging, especially for someone l ...

JavaScript alerts

Can anyone recommend a quality library with beautifully animated popups? Specifically, I need a popup that allows for basic HTML fields such as text areas and more.... I am in search of a popup that will overlay on the current page, rather than opening a ...

Ways to customize the datetime-local format in an HTML input field

When dealing with the HTML input of datetime type, consider the following: Datefield: <input type="datetime-local" data-date="" data-date-format="DD MMMM YYYY, h:mm:ss"> The script below includes important code. $("input").val(moment().format(&apo ...

PHP problem with submitting an array of checkboxes

Having an issue with checkbox array This is the code snippet <?php include('config.php'); if(isset($_POST['submit'])) { for($x = 0;$x <= 5;$x++) { if(isset($_POST['check'][$x])) { ...

Executing a function enclosed in parenthesis does not yield any output

My code is supposed to print the sender's name followed by "adopted" and then the first mentioned user. const { Client } = require('discord.js', 'async', 'discord-message-handler'); const bot = new Client(); const cfg = ...

Is it possible to pass image data response from jQuery .ajax into a new AJAX call?

Currently, I am attempting to combine the ImageOptim API with the OCR.space API. Both APIs are exceptional, and I cannot recommend them highly enough! However, a challenge arises as the OCR API only accepts images under 1mb or 2600x2600 px in the free tier ...

Activate the q-file toggle for the Quasar framework when a different button is selected

How can I make the file selector q-file toggle in Quasar framework when a specific button is clicked? My current attempt: When this button is clicked, it should toggle the q-file: <button @click="toggleFileSelector">Toggle File Selector&l ...

Merging object keys and values from JSON arrays based on their keys, using JavaScript

Is there a way to merge object keys' values from JSON arrays based on their key? json1 = [ {key:'xyz', value:['a','b']}, {key:'pqrs', value:['x','y']} ] json2 = ...

Transforming timestamps to month day, year format and back again without the use of any NPM packages

I have developed a microservice that converts Unix timestamps to a format like Dec 01, 2017 and vice versa. The microservice is deployed at this link: timestamp I am wondering if there is a better way to achieve this without using third-party NPM modules. ...

Vue.js Components Facing Build Issues

I am currently experiencing a puzzling phenomenon. While working on my application components using Laravel Jetstream and Inertia Stack with VueJS, I encountered an issue where a newly created component in the same folder as others was not building. Neithe ...

What is it about Kyle Simpson's OLOO methodology that seems to swim against the tide of Typescript's popularity?

Disclaimer: this post might come across as impulsive. Warning for Typescript beginners! Also, a bit of a vent session. Recently, I delved into the OLOO approach from the YDKJS book series within a Typescript and Node environment. // ideal JS syntax le ...