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

I am new to javascript and jquery. I have encountered numerous cases involving audio players

Recently delved into learning javascript and jquery. I managed to create a basic audio player that plays short audio clips. However, I've encountered an issue where clicking the play button on one clip displays stop buttons on all clips instead of on ...

How come my dynamic source path doesn't function correctly unless I add an empty string at the end of it?

Recently, I encountered an issue while using Vue.js to dynamically create a source attribute using an object's properties. Here is the code snippet where I faced the problem: <img :src='"../assets/" + project.image.name + "." + project.image. ...

Display various JavaScript function outputs in an HTML table for convenient tracking

Thanks to a helpful user on this platform, I was able to capture data from a JavaScript function and display it in an html table. However, I now have another query. How can I execute the function multiple times during page load and record the results in ...

Troubleshooting Recursive Logic Problem with hasOwnProperty in JavaScript and JSON

JSON data with a specific problem highlighted by the comment // doesn't get parsed currently: var oarsObject = [{ "coordinateReferenceSystem": "26782,15851 <-- not in a value", "positionReferenceType": "geogWgs84", "geogWgs84": ...

How can I implement Jquery validation engine ajax for two different fields using the same function?

The jQuery validation engine plugin has a unique feature of performing ajax validation. However, there is a minor inconvenience with this functionality. Instead of validating the field name, it sends the field ID for validation. Why does this pose a prob ...

Uncovering the Issue with Select All Functionality in <Table/> when using Material-UI and React

When using Material-UI's <Table/> with ReactJS, a table is set up with a select all checkbox. Each time an individual row checkbox is clicked, the row id is added to the state array clickedRowIds. This allows for logging of the ids of the clicke ...

Manipulating an element in the JSON data is causing alterations to the preceding elements

I am facing a challenge with two JSON arrays. $scope.arr1 = [ { "id": 1, "first_name": "Philip", "last_name": "Kim", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1e6e7577732e5e737b7a777f78776c7b307d717 ...

The AJAX request for JSON data is functioning correctly in Firefox, but is experiencing compatibility issues with other web browsers

I recently completed a PHP page that generates a valid JSON document. The jQuery code used to fetch and display the data is quite straightforward: $.ajax({ url: "http://localhost:8888/rkm/json-jc", dataType: "json", success: function(data) { ...

Ways to apply autofocus to one element once another element already has it?

I have encountered an issue while attempting to give a textarea autofocus using the autofocus attribute. Upon doing so, I receive an error message in the console that says: Autofocus processing was blocked because a document already has a focused element. ...

Turning PHP array into JSON using Zend RPC

Greetings, I am facing a small issue that I need help with. Currently, I am developing a RPC service using ZendFramework and Apigility which requires the response to be in a json array format. Below is the content negotiation code snippet that I have imple ...

Editable content area: Maintain and restore cursor position when placed on a blank line

While working with a contenteditable div and constantly updating the HTML as the user types, I am facing the challenge of saving and restoring the caret position. I came across a helpful solution provided by Tim Down on a similar issue, which I found on S ...

The webpage is failing to refresh even after using history.push()

While working on my React dictionary project, I encountered an issue with React Router. After using history.push() with the useHistory hook from react-router, the page does not re-render as expected. I have a search bar and utilize this function to navigat ...

Ways to efficiently handle numerous asynchronous requests in a NodeJS/Express API

I am looking to consolidate a variety of REST APIs into a single, easy-to-use API. My plan is to develop a straightforward nodejs/express API that will handle the individual calls asynchronously and then aggregate all the results together at once. The Jav ...

React js background image not filling the entire screen

Having experience with React Native, I decided to give ReactJS a try. However, I'm struggling with styling my components because CSS is not my strong suit. To build a small web application, I am using the Ant Design UI framework. Currently, I have a ...

Button within ng-switch statement

Issue with switch button inside switch statement, only functioning correctly outside of the switch statement. See below for my code: <div ng-controller="LoginController as LC"> <div ng-switch on="view.name"> <div ng-switch-de ...

Guide to inputting text into the Dev element

I am encountering a challenge with automating gist creation on GitHub. The issue arises when trying to input text into the gist content-box (see attached image). Despite attempting to use Javascript executer, I have not been successful. JavascriptExecutor ...

Exploring content within a nested directory on AWS S3

I'm currently experimenting with an ajax request in order to retrieve all image files from a specific subfolder within my S3 bucket. Even though I have set the subfolder to public access using the dropdown menu (view image for reference), I keep enco ...

Creating an if statement that validates whether all variables have non-null values

I am still getting the hang of javascript and working on some coding projects from my textbooks. The current task involves creating an if statement to check if the values of the elements referenced by the names fname, lname, and zip are all not null. Here ...

Importing a file using its absolute path in JavaScript

Within the dependencies directory, there exists a module named foo: import foo from '../dependencies/foo'; // This import statement works as intended The challenge arises when attempting to import from a different path due to deployment in an AW ...

Update the JSON data following deletion

I have received the following JSON data: "memberValidations": [ { "field": "PRIMARY_EMAIL", "errorCode": "com.endeavour.data.validation.PRIMARY_EMAIL", "createdDateTime": null }, ...