Could there be a mistake in the way array combinatorics are implemented in JavaScript?

Having encountered the necessity for generating unique combinations when dealing with multiple arrays, I developed this script. While it functions as intended during the combination process, storing the result in a final array yields unexpected outcomes.

let options = {
    "A": ["A1", "A2", "A3", "A4"],
    "B": ["B1", "B2"],
    "C": ["C1", "C2", "C3", "C4", "C5"],
};

let keys = Object.getOwnPropertyNames(options);
let size = keys.length;

let final = [];

function combinate(n, o) {

    for (let i = 0; i < options[keys[n]].length; i++) {

        if (n === (size - 1)) {
            o = {};
        }

        o[keys[n]] = options[keys[n]][i];

        if ((n - 1) >= 0) {
            combinate(n - 1, o);
        }

        if (n === 0) {
            console.log(o);
            final.push(o);
        }

    }

}

if (size > 0) combinate(size - 1, {});

console.log("-----------------------------------")
console.log(final);

Answer №1

Instead of storing the same object multiple times in your array and modifying it, you should add a new copy of the object to the array.

Replace: final.push(o); with

final.push(Object.assign({}, o));

Alternatively, you can do it more succinctly like this:

final.push({A:o.A, B:o.B, C:o.C});

Answer №2

To achieve the desired outcome, pass the object's reference into the function and then append the modified object to the final array.

let choices = {
    "X": ["X1", "X2", "X3", "X4"],
    "Y": ["Y1", "Y2"],
    "Z": ["Z1", "Z2", "Z3", "Z4", "Z5"], };

let categories = Object.getOwnPropertyNames(choices); 
let count = categories.length;

let finalArr = [];

function combine(idx, newObj, result) {

    for (let j = 0; j < choices[categories[idx]].length; j++) {

        if (idx === (count - 1)) {
            newObj = {};
        }

        newObj[categories[idx]] = choices[categories[idx]][j];

        if ((idx - 1) >= 0) {
            combine(idx - 1, newObj, result);
        }

        if (idx === 0) {
            console.log(newObj);
            result.push(newObj);
        }

    }
    if(idx===count-1){
      return result;
    }

}

if (count > 0){
  finalArr = combine(count - 1, {}, []);
}

console.log("-----------------------------------");
console.log(finalArr);

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 library for making HTTP requests

Can someone provide guidance on creating a JavaScript command line application that interacts with a public API using an HTTP client library? What is the preferred JavaScript HTTP library for this task? ...

Altering the context of 'this' with the bind method in JavaScript

When using bind to change the scope of 'this', it allows me to reference my generateContent function using 'this' within the click function. However, this adjustment causes the this.id to no longer work due to the changed scope. Is the ...

Employ an asynchronous immediately-invoked function expression within the callback

Can an asynchronous IIFE be used inside the callback function to avoid the error message "Promise returned in function argument where a void return was expected"? You can find an example here. signIn(email: string, password: string, course?: ICourse): ...

Enhancing OpenAI API Responses with WebSocket Streaming through Express Middleware Integration

  Currently, I am in the process of developing an Express.js application that requires integration of OpenAI's streaming API responses to be transmitted in real-time to a front-end via WebSockets. Even though I have established communication between ...

Encountering issues while trying to establish a connection to MongoDB through JavaScript

I have developed a code for seamlessly integrating various social networking logins with nodejs. Below is my server.js file: // include the necessary tools var express = require('express'); var app = express(); var port = process.env ...

Updating the date with setState in Material UI components

I have a question about integrating the material ui datepicker into my project. I want the current date in the state to update whenever the user switches from one date to another. You can find the materialUi datepicker I am using at this link. I tried im ...

Uploading files using Multipart/form-data in Node.js and Express.js

With the removal of express.multipart from the Express 4.x library, what approach would be most effective for managing file uploads in expressjs? ...

NavigAuth - NativeScript Vue's Innovative Authentication-driven Navigation

After spending hours trying to figure this out, I need to ask for help. How can I create a simple Auth-based Navigation within my App? I have successfully set up a Firebase auth user inside my Vuex using an auth listener. Now, all I want is to display th ...

The functionality to move forward and backward in Modal Bootsrap seems to be malfunctioning

I am in need of assistance as I have encountered a major issue that has halted my work progress for several days. My goal is to implement a feature that allows users to navigate between different days both forwards and backwards. While the functionality it ...

Leveraging the power of ES6 syntax in Node scripts with Babel

My npm CLI tool utilizes ES6 syntax from BabelJS, specifically arrow functions. Within the entry point of my tool, I'm using the following require: require('babel-core/register'); var program = require('./modules/program.js'); I ...

Trouble with Bootstrap 5 Dropdown Functionality

Currently, I am using Bootstrap 5 in conjunction with Django to create a website and I'm encountering difficulties with getting a dropdown feature to work properly. Despite copying the code directly from w3schools, it fails to function when I load the ...

I'm a beginner with Angularjs and I attempted to populate multiple JSON values, but unfortunately, it didn't work as expected

<div ng-controller="studentController" ng-repeat = "student in students | unique = 'RollNo' " > <table class="profile-info"> <tr> <th>Enrollment Number</th> <td> ...

Is it possible to pass the image source to a Vue.js component through a

I am encountering an issue while trying to display an image in the designated location within display.vue. Even though {{ someText }} returns the correct file path (../assets/city.png), the image is not being output correctly. Here is how my code looks: ...

Tips for inserting a personalized image or icon into the ANTD Design menu

Can anyone help me figure out how to replace the default icons with a custom image or icon in this example: https://ant.design/components/layout/#components-layout-demo-side I attempted to do it by including the following code: <Menu.Item to="/" key=" ...

Upon loading the page, trigger the controller method by utilizing the information from the query string

Can query string data be retrieved on page load with javascript? Here is how I am attempting to achieve this in my project: The view page displays tabular data. When a button is pressed, it retrieves the row's id and invokes a javascript function. ...

Because of the CSS tree structure, it is not possible to add or remove classes. This restriction applies to all actions done in jQuery, including click

I want to create a hover effect where the CSS changes when hovering over an item, then reverts back to normal when no longer hovered. Additionally, I would like the CSS to change when the item is selected, and return to normal when another item in the same ...

How can I display an array with keys from php in AngularJS using ng-repeat?

I have a rootScope variable that will store product categories, each category may or may not have child categories. Here is how I assign the rootScope: $rootScope.categoryList = $http.get('category').then((result) -> result.data) This code s ...

Transforming a mathematical expression stored as a string into an array

Is there a simpler way to convert a String like 1+40.2+(2) into a String array [1, +, 40.2, +, (, 2, )] for a Shunting Yard algorithm in my Calculator class? Due to input being entered without spaces, input.split("\\s+") won't work. I' ...

Importing the class results in an undefined outcome

In the process of developing my Vue app, I'm focusing on creating some helper classes: File a.js: export default class Base {//...} File b.js: import Base from "./a" export default class Middle extends Base { // ... } File c.js: import Mi ...

When a React page is re-rendered using useEffect, it automatically scrolls back to the

Every time I utilize the <Tabs> component, the onChange method triggers the handleTabChange function. This leads to the component being called again and after repainting, the useEffect is triggered causing the page to scroll back to the top. How can ...