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

Error discovered in Webpack syntax

I'm a newcomer to webpack and feeling lost on how to properly configure the settings. Here is my project structure: / -- /public -- /js -- app.js -- /css -- app.scss -- /node_modules -- /autoprefixer -- /babel-loader ...

How to effectively use the LIKE statement in mysql with node.js

app.post('/like/:level/:name', function(req, res){ connection.query("SELECT * from books where " + req.params.level + " like '%" + req.params.name + "'%", function(err, rows, fields) { if (!err){ var row = rows; res.send(row); console.l ...

Tips for implementing the JSON object table filter functionality

My website features a collection of json objects organized as shown below: [ { "a": true or false, "b": "information", "c": "information", "d": "information", "e": "information" }, ... ] The goal here ...

What is the best way to apply custom styles in reactJs to toggle the visibility of Google Maps?

There are three radio buttons that correspond to school, restaurant, and store. Clicking on each button should display nearby locations of the selected type. Displaying Google Map and nearby places individually works fine without any issues. class Propert ...

Testing infinite scrolling with the help of protractor

It seems like the infinite scrolling feature in ng-grid is not exactly infinite, but it's the closest comparison I could come up with for what I am observing. In our application, we are using ng-grid to display data in a table with approximately 170 ...

Can jQuery.jScrollPane be set to consistently display a vertical scroll bar?

Can jQuery.jScrollPane be configured to consistently display a vertical scroll bar? Is there a hidden setting or API function that can achieve this? Ideally, without needing to adjust the content pane's height or other properties. ...

development session not persisting on local server (localhost:4200)

Currently, I am utilizing angular for the frontend and node.js along with express for the backend of my application. The interesting observation is that when I run the app on localhost:3000 (the designated port for the express app), everything operates cor ...

Learn how to seamlessly connect lists in Vue with these foolproof steps

<template> <div class="lists"> <div v-for="(list, key, i) in getAllBreeds" :key="i"> <div v-if="list.length"> <div v-for="(ele,i) in list" ...

Show the Vue.js template in a Laravel Blade view

I have been struggling to integrate a Vue.js component into a Laravel blade file. Despite researching tutorials and Stack Overflow solutions, I have not been able to resolve the issue. Below is the template that I want to display: <template> < ...

How can I adjust the timeout or enhance my code for Excel Online's ExcelScript error regarding the Range getColumn function timing out?

I am struggling with a code that is supposed to scan through the "hello" sheet and remove any columns where the top cell contains the letter B: function main(workbook: ExcelScript.Workbook) { let ws = workbook.getWorksheet("hello"); let usedrange = ws ...

underscore.js provides _.where utility for filtering arrays of strings and objects

I am looking to verify whether a specific string is present in a collection of objects. The variable this.props.value contains the string "apple, peach" and this.state.list consists of a list of objects with key-value pairs. My goal is to determine if "ap ...

Need help triggering Ajax code upon clicking a link?

Can someone help me find the issue with my script? Below is the code snippet: <script> $(".icross").click(function(e){ e.preventDefault(); var obj = $(this); $.ajax({ type: "GET", url: "supprimer.php", data: 'id=&a ...

Tips for showing a DialogBox when a blur event occurs and avoiding the re-firing of onBlur when using the DialogBox

Using React and Material UI: In the code snippet provided below, there is a table with TextFields in one of its columns. When a TextField triggers an onBlur/focusOut event, it calls the validateItem() method that sends a server request to validate the ite ...

The 'gulp-jade' plugin seems to be malfunctioning and failing to properly compile jade files into HTML documents

Currently, I am immersed in a project where I rely on using gulp. My main objective is to compile the jade files I create (found in the _jadefiles folder) and have them output as .html files in the _includes folder within my project. The current list of t ...

Next.js: Generating static sites only at runtime due to getStaticProps having no data during the build phase, skipping build time generation

I am looking to customize the application for individual customers, with a separate database for each customer (potentially on-premise). This means that I do not have access to any data during the build phase, such as in a CI/CD process, which I could use ...

Issue with array push not working within nested Promise

I recently encountered an issue with my Express API route that retrieves an artist's details along with an array of releases for that artist. My current goal is to iterate over this array, extract each URL, and then make additional API calls to retri ...

The click event for getelementbyid() function is malfunctioning

I need assistance with a website I am creating that plays audio when a certain condition is met. Specifically, I want the audio to play if x falls within a specific range of numbers, but also continue playing if x does not fall within that range after th ...

Choosing a single item from multiple elements in React using React and typescript

In this particular project, React, TypeScript, and ant design have been utilized. Within a specific section of the project, only one box out of three options should be selected. Despite implementing useState and toggle functionalities, all boxes end up bei ...

How can Reactjs access a configuration file?

I am struggling to find a solution for reading a properties file in reactJS. I have come across the "properties-reader" module but I can't figure out how to make the require function work. Is there an easier way? For instance, import React, { Com ...

Discover the most helpful keyboard shortcuts for Next.js 13!

If you're working with a standard Next.js 13 app that doesn't have the experimental app directory, setting up keyboard shortcuts can be done like this: import { useCallback, useEffect } from 'react'; export default function App() { c ...