What ways can I leverage JavaScript to convert a provided array into multiple different arrays?

I am in need of a function that meets the following criteria:

  • Given the dimensions of an array, return all possible combination arrays based on the given numbers.
  • The length of the given array should be equal to the length of the array returned.
  • The size of the combinations should be the result of multiplying the numbers in the given array. For example: given [2, 2], the size would be 2*2=4; given [2, 1, 2], the size would be 2*1*2=4.
  • Subtracting 1 from the number in the given array gives you the maximum number for that column.

I understand it might not be very clear, so let's look at some examples:

given: [1, 1]
return: [[0, 0]]

given: [2, 2]
return: [[0, 0], [0, 1], [1, 0], [1, 1]]

given: [2, 3]
return: [[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2]]

given: [3, 3]
return: [[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2]]

given: [1, 1, 1]
return: [[0, 0, 0]]

given: [1, 1, 2]
return: [[0, 0, 0], [0, 0, 1]]

given: [2, 1, 2]
return: [[0, 0, 0], [0, 0, 1], [1, 0, 0], [1, 0, 1]]

given: [2, 2, 2]
return: [[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1]]

Is there a way I can implement this function using lodash, Immutable.js, or any other libraries? Thank you.

===========UPDATED===========

I have finally resolved the issue by utilizing the cartesian product feature of js-combinatorics along with lodash.
Firstly, I was able to easily convert the given array into separate arrays:

import _ from 'lodash';

const givenArr = [2, 1, 2];
const arr = givenArr.map((v) => _.range(v)); 
console.log(arr); // [[0, 1], [0], [0, 1]]

Then, passing these transformed arrays to the js-combinatorics API as follows:

const cp = Combinatorics.cartesianProduct([0, 1], [0], [0, 1]);
console.log(cp.toArray()); 
// [ [ 0, 0, 0 ], [ 1, 0, 0 ], [ 0, 0, 1 ], [ 1, 0, 1 ] ]

Answer №1

After the recent update, I have gained a better understanding of the issue at hand.

For a potential solution, my suggestion would be to utilize a recursive approach. Below is some pseudocode that outlines the process:

function findPotentialCombinations( inputArray ) {

  if inputArray contains only one element {
    return a list with all possible values
  }

  firstElement = retrieve the first element from the input array

  updatedInput = inputArray with the first element removed

  subSolution = findPotentialCombinations( updatedInput )

  finalResult = empty list

  for each possible value for the first element of the result as newElement 
  (can be listed using firstElement) {
    merge newElement with subSolution and add to finalResult
  }

  return finalResult
}

The concept behind this approach involves removing the first element from the input, recursively generating solutions for the smaller inputs, and then combining these solutions with every feasible element derived from the initial first element.

An important consideration is the base case, where the input array consists of just one element. In such instances, the output will be a list encompassing all plausible values for that particular element.

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

JavaScript Astro file not triggering window.onload event

I need assistance with my Astro components in my App: apps/myProject libs/components/header Within the header.astro component, I have a script that should execute once the entire page is rendered: <script is:inline> console.log('hello!' ...

Errors are not displayed or validated when a FormControl is disabled in Angular 4

My FormControl is connected to an input element. <input matInput [formControl]="nameControl"> This setup looks like the following during initialization: this.nameControl = new FormControl({value: initValue, disabled: true}, [Validators.required, U ...

Switching the endpoint renders the middleware ineffective

I've encountered a puzzling issue with my NodeJs - Express server, which serves as the backend for my mobile application. The problem arises when I send post requests to certain endpoints like checkmail and checkusername using axios from the frontend ...

I am configuring Jest in my Vite and TypeScript-powered React project

I am having trouble with the relative path of the file I imported in App.test.tsx. It keeps showing me this error message: Cannot find module '@/components/items/card.tsx' from 'src/__tests__/App.test.tsx' Below is the code snippet: // ...

Problems Arising from the Combination of Django and External JavaScript

I am currently working on a project that uses Django 1.11 and JavaScript, but I am encountering an issue. The JavaScript code works fine when run within the HTML file, as it successfully loads the JSON data. However, when I move everything to the static fo ...

Enhancing AngularJS routing with dynamic partial parameters

I have experience working with routes in different frameworks like Rails and Laravel, but I am now facing a challenge while working on an AngularJS site. In Laravel, we could dynamically create routes using foreach loops to handle different city routes. Ea ...

NodeJS API Language Configuration

I'm currently working on integrating the DuckDuckGo Instant Answer Api into my NodeJS application. To do so, I am making a data request from the API using Node Request. var request = require('request'); request('http://api.duckduckgo.c ...

Every time the page is refreshed, the value stored in React localStorage gets

After adding a new item to the list, the local storage gets updated. However, upon page refresh, I noticed that the key remains but the value is reset to an empty array. import { useState, useEffect } from 'react'; function App() { const [data ...

Express 4 Multer shows an error where req.body and res.json are not defined

As I attempt to achieve a single image file upload along with text fields using Express 4.0 and multer 1.1.0, I am facing certain challenges. The image file is successfully uploaded to the designated location, but issues arise with the text fields and resp ...

Combining hover and mousedown event listeners in jQuery: Tips and tricks

htmlCODE: <div class="original_circle" style="border-radius: 50%; background-color: blue; width: 40px; height:40px; z-index: 0"> <div class="another_circle" style="position:absolute; border-radius: 50%; background-color: coral; width: 40px; h ...

Is it possible to enlarge a div using "display: table-cell" property when clicked on?

There are various components displayed on my webpage: I require all components to have a minimum height of 150px. If the height is less than 150px, I want to vertically center their text. In case the height exceeds 150px, I aim to truncate the text at 15 ...

What is the process for uploading images in the backend of a Next.js API?

I am working with Next.js and an API. I need to be able to upload two files and include one text input field using the API backend. I have been struggling to find a solution for uploading files with different fields along with a single text input field in ...

Excessive image display | HTML and CSS synergize

I am having some trouble with my image gallery. Each image is displayed as a vertical column and has zooming effects when hovered over. Clicking on an image should show it in full screen with a caption. The problem arises when dealing with images that are ...

The input field will be in a read-only state if it contains a value from the database. However, it will be editable if the value

Hello everyone, I am a newcomer to this community and would greatly appreciate your help. I am encountering an issue with the following lines of code: <input type="text" class="form-control" id="fines" name="fines&quo ...

"PHP and Javascript Validation Library: Building Confidence in Your Data

Looking for a PHP form validation library that can work independently outside of any PHP framework? It should be able to handle basic validations like checking for empty fields, using regex, validating email addresses, and alphanumeric characters. Ideally, ...

Concealing a section of a table with JavaScript while preserving the original table structure

I made some adjustments to the script tag: $(document).ready(function) { Now, the evenTd's are hidden correctly. Here is the table with the code provided: <table> <tr> <td>itemOne</td> <td class="even ...

Using jQuery, set a restriction on the total number of options in three dropdown menus to

I am currently facing a challenge with 3 dropdowns, each containing 8 options. My aim is to restrict the total selection across all three dropdowns to 8. For instance, if I choose 7 in the first dropdown, I should only be able to pick 1 in the next two. Si ...

Is there a way to extract the HTML source code of a website using jQuery or JavaScript similar to PHP's file_get_contents function?

Can this be achieved without a server? $.get("http://xxxxx.com", function (data) { alert(data); }); I have tried the above code but it seems to not display any output. ...

Creative Solution for Nested Forms

I am currently facing a challenge with nested forms in my PHP project. I need to include a form for AJAX image upload within another form so that I can pass the file path to the main form. The example code snippet is provided below; <form> <f ...

Integrate a feature in React-native MapView that dynamically swaps out markers with different images

Thanks to the insights shared in this informative article, I successfully integrated observations into my MapView. mapMarkers = () => { return this.state.items.map((item) => <Marker key={item.id} coordinate={{ latitude: item.g ...