Is it possible to utilize recursion for adding new values in multidimensional arrays in this scenario?

how do we add a new value to each array in the container if the number of fruits is less than the desired target?

for example:

- we need to add new fruits to these 2d arrays:
 - The maximum number of "apple" in a container should be 3 fruits,
    if there are more, we add them to a new array/index in the next 2d array container.
 - The maximum number of "mango" in a container should be 2 fruits,
    if there are more, we add them to a new array/index in the next 2d array container.
 - The maximum number of "stawberry" in a container should be 4 fruits,
    if there are more, we add them to a new array/index in the next 2d array container.

const stawberry = x => {
     return x.filter(el => el === "stawberry").length;
  }

const apple = x => {
     return x.filter(el => el === "apple").length;
  }

const mango = x => {
     return x.filter(el => el === "mango").length;
  }

const fruits = kindOfFruits => {

  if(kindOfFruits.length === 0){
    return [];
  } else if(stawberry(kindOfFruits[0]) === 0 ){
    kindOfFruits[0].push("NEW STAWBERRY");
  }
  return kindOfFruits.concat((fruits(kindOfFruits.slice(1))));
}

const container = [
  ["apple", "apple", "banana", "mango", "stawberry", "banana", "banana"],
  ["banana", "mango", "stawberry", "stawberry"],
  ["apple", "mango", "mango"]
];

console.log(fruits(container));

The desired RESULT should look like this:

[
  ["apple", "apple", "banana", "mango", "stawberry", "banana", "banana", "apple", "mango", "stawberry ", "stawberry", "stawberry"],
  ["banana", "mango", "stawberry", "stawberry", "apple", "apple" , "stawberry"],
  ["apple", "mango", "mango"]
];

NOTE: The order of the fruits doesn't matter when adding them, as long as the correct number is reached.

The containers are already set up, we just need to populate them with fruits according to the rules mentioned above.

I hope my explanation makes sense, please let me know if it's unclear.

Answer №1

Your question lacks clarity as there are gaps in the information provided, such as the specific target and the types of fruit that should be present in the container.

Based on my interpretation, it seems you are trying to populate a 2D array based on certain targets. Here is a snippet of code that may help:

    var appleTarget = 5;
    var orangeTarget = 7;
    var bananaTarget = 10;
    var fruits = ["apple", "orange", "banana"];

    function countFruit(container, fruit) {
        return container.filter(item => item === fruit).length;
    }

    function addFruitToContainer(dimension, fruit) {
        dimension.push(fruit);
    }

    function fillContainer(fruitContainer) {
        var selectedTarget;

        fruits.forEach(function(fruitType) {
            fruitContainer.forEach(function(dimension){
                if(fruitType === "apple") selectedTarget = appleTarget;
                else if(fruitType === "orange") selectedTarget = orangeTarget;
                else if(fruitType === "banana") selectedTarget = bananaTarget;
                else selectedTarget = 0;

                var fruitCount = countFruit(dimension, fruitType);

                if(fruitCount < selectedTarget) {
                    for(var i = selectedTarget - fruitCount; i > 0; i--) {
                        addFruitToContainer(dimension, fruitType);
                    }
                }
            });
        });

        console.log("Filled container:");
        console.log(fruitContainer);
    }

    var container = [
        ["apple", "apple", "pear", "orange", "banana", "pear", "pear"],
        ["pear", "orange", "kiwi", "kiwi"],
        ["apple", "orange", "orange"]
    ];

    fillContainer(container);

Answer №2

A strategy involving identifying similar items to the new item, counting them, and comparing against a predetermined maximum before deciding where to place it in the sequence. If the count is less than the desired limit, the new item is added at the current index; otherwise, it is placed after the current index.

This method operates on an array of items, examining each item to determine its compatibility with the given container.

function addFruit(fruit) {
    const 
        addFruits = (s, v) => s + +(v === fruit),
        max = { apple: 3, mango: 2, stawberry: 4, default: Infinity };

    var i = 0;

    while (i < container.length) {
        if (container[i].reduce(addFruits, 0) < (max[fruit] || max.default)) break;
        i++;
    }
    container[i] = container[i] || [];
    container[i].push(fruit);
}


var data = ["apple", "apple", "mango", "stawberry", "banana", "mango", "stawberry", "banana", "apple", "apple", "stawberry", "banana", "apple", "mango", "stawberry", "stawberry", "stawberry", "banana", "stawberry"],
    container = [];

data.forEach(addFruit);

console.log(container);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

Switching function handlers between elements in the d3 DOM framework

I have developed a piece of code that is designed to transfer event handlers from one element to another while removing them from the previous control. You can see the functionality in action on this fiddle: http://jsfiddle.net/pydty4bq/ var slider = d3.s ...

Issue with splitting a JavaScript function in JQuery within the Wordpress platform can cause errors

My split function seems to be causing an error, as shown in this console error image. There is a hidden input field within the PHP file: <input class="file-id" name="_file-id" type="hidden" value="<?php echo esc_attr($file_ids); ?>" /> I hav ...

Facing a problem with jQuery where variables are lost when using $(document).on

I am facing an issue with my code - when I remove the (doc on), it works fine until the div is reloaded. However, after the reload, the buttons stop working. When I add (doc on), the event triggers but drops the variables. Any suggestions? $(document). ...

Display the status in the textbox once a dropdown value has been selected

I have a function that allows me to add shops. Within this function, I am able to select whether the shop is OPEN or CLOSED. The goal is for the status of the shop, either OPEN or CLOSED, to appear in a textbox on another modal. When creating a user and ...

Iterate through every multi-dimensional array and output a single array

This is a multidimensional array: Array ( [CalculateOverheadDoorSpringsResult] => Array ( [SpringForce] => Array ( [InputData] => Array ( ...

Can you tell me the distinction between using RemoteWebDriver's executeScript() and Selenium's getEval() for executing

Can you explain the distinction between these two pieces of code: RemoteWebDriver driver = new FirefoxDriver(); Object result = driver.executeScript("somefunction();"); and this: RemoteWebDriver driver = new FirefoxDriver(); Selenium seleniumDriver = ne ...

Storing the array with the highest length in a temporary array using Javascript

I am currently working with two arrays that can be of equal length or one may be longer than the other. My goal is to determine the longest array if they are not equal in length, and then use this length to control a loop. $.ajax({ url: "/static/Dat ...

Finding the Sum and Average of an Array

Currently tackling a challenging array problem as part of my college course. I am striving to calculate both the sum and average of an array. Below is the code I have managed to put together so far: public class Module55 { public static void main(Strin ...

Implement a jQuery slider that pauses on hovering

Currently, I am grappling with the clearInterval function in a small jQuery project. To better illustrate the issue, I have created a jsFiddle example: http://jsfiddle.net/eWTSu/ While the rotation works smoothly, I encountered an obstacle when hovering ...

"Utilizing Ramda's map function to integrate dynamic keys: A step-by-step guide

I am currently working with an array structured like this : array = ['2020-06-03', '2020-06-05', '2020-06-06'] My task is to transform it into the following format : Object { "2020-06-03": Object { "selec ...

Using jQuery to target specific content within a div element

Currently in the process of developing a small text editor, I am seeking to implement a feature that allows users to select text similar to the effect demonstrated here: After exploring the idea of utilizing the jQuery select event for this purpose, I enc ...

Tips for dynamically appending a string to a predefined variable in React

When I was working on creating a text input space using the input type area and utilizing the onChange utility, everything was running smoothly. Now, my task is to incorporate an emoji bar and insert a specific emoji into the input space upon clicking it. ...

What is the best way to update a nested property in an object?

Consider the following object: myObject{ name: '...', label: '...', menuSettings: { rightAlignment: true, colours: [...], }, } I want to change the value of rightAlignment to fals ...

Slowly revealing sticky navigation with slideDown animation using JQuery

Here is the code for a .JS file: $(document).scroll(function (){ var menuheight= $('header').height(); var y = $(this).scrollTop(); if (y>(menuheight)) { $('.menu_nav_features').addClass ...

<select> Choices are updated without the need for AJAX

Question I am working on a project with two dropdown select inputs. The first one is for selecting the country and the second one is for choosing a more specific location within that country. For example, if you choose "United Kingdom" as the country, you ...

What is the best way to retrieve the parent iFrame ID when a blur event occurs in the TinyMCE

I have successfully implemented 4 TinyMCE editors on a single page. My goal is to obtain the editor ID when the user exits the TinyMCE editor and place the editor's HTML content into a textarea. While I can achieve this using the blur event in Chrome, ...

Assigning a variable in jQuery to a PHP variable that has not been defined can halt the script

Here is the code snippet for a document ready function: $(document).ready(function(){ var id = <?php echo "" ?>; alert('boo'); if(id!=0){ $(' ...

Transferring Variables to the Following Page Without Using a Form or Changing the URL

I have a question about passing a variable along with a link to exampleA.php without using URL extensions or form submitting. I've done some research and found that most people suggest using Ajax, but I want to handle the variable once I'm on the ...

There seems to be a hiccup in the JavaScript Console. It could potentially impact the functionality

Hey there, I'm encountering a strange issue in my IE 11 console. A JavaScript Console error has occurred. This may impact functionality. Whenever I try to run a for loop to create a list of elements within a ul tag 4000 times, the process stops at ...

Is it possible to directly utilize functions from an imported JavaScript library, such as Change Case, within the template of a Vue component?

After successfully importing and using the Change Case library within the <script></script> element of a Vue component, I now seek to directly utilize the Change Case functions in the template itself. As of now, my understanding is that when d ...