In JavaScript, loop through an array of arrays and combine them using the concat

If I have an array like [["a", "b"], ["c", "d"]], is there a way to iterate, reduce, map, or join this array in order to get the desired output of ["ac", "ad", "bc", "bd"]? What if the array is structured as

[["a", "b"], ["c", "d"], ["e", "f"]]
; how can we then obtain
["ace", "acf", "ade", "adf", "bce", "bcf", "bde", "bdf"]
?

Is it possible to achieve this using array iteration methods?

I attempted to use the reduce method:


const output = [];
const solution = array.reduce((cumulative, individual) => {
  for (let i = 0; i <= cumulative.length; i++) {
    for (let j = 0; j <= individual.length; j++) {
      output.push(`${cumulative[i]} + ${individual[j]}`);
    }
  }
});
console.log(output);

However, my code did not produce the exact desired output.

Answer №1

One possible solution is to implement a recursive function that iterates over the arrays, concatenating each element with the results from the subsequent arrays:


const concatenateArrays = (arrays) => {
  const currentArray = arrays.shift();
  
  if (!currentArray) return;
  
  const result = [];
  
  for (const nextElement of concatenateArrays(arrays) || ['']) {
    for (const char of currentArray) {
      result.push(char + nextElement);
    }
  }
  
  return result;
}

const arraysToConcatenate = [["a", "b"], ["c", "d"], ["e", "f"]];
console.log(concatenateArrays(arraysToConcatenate));

Answer №2

You can achieve this by using the reduce and flat methods

arr1= [["a", "b"], ["c", "d"]] ;
arr2=[["a", "b"], ["c", "d"], ["e", "f"]];
arr3=[["a", "b"], ["c", "d"], ["e", "f"],, ["g", "h"]];
function combineArrays(arr) {
  return arr.reduce(function(a, b) {
     return a.map( function(x) { return b.map(function(y) { return x.concat([y])})}).flat().flat()}, [[]]);
}
console.log(combineArrays(arr1)); 

console.log(combineArrays(arr2));

console.log(combineArrays(arr3));

Answer №3

To achieve this, you can utilize a single `for` loop paired with recursion. In this method, you maintain one parameter to track the index of the current sub-array on which the `for` loop is operating. This process involves incrementing that value at each level. This technique is commonly known as the Cartesian product.

const data = [["a", "b"], ["c", "d"], ["e", "f"]]

function cartesian(data, prev = '', n = 0) {
  const result = []

  if (n >= data.length) {
    result.push(prev);
    return result;
  }

  for (let i = 0; i < data[i].length; i++) {
    let val = prev + data[n][i];
    result.push(...cartesian(data, val, n + 1))
  }

  return result;
}

console.log(cartesian(data));

Another approach involves using the `reduce` method, which generates recursive calls only when the current `n` value is less than `data.length - 1`.

const data = [["a", "b"], ["c", "d"], ["e", "f"]]

function cartesian(data, prev = '', n = 0) {
  return data[n].reduce((r, e) => {
    let value = prev + e;

    if (n < data.length - 1) {
      r.push(...cartesian(data, value, n + 1))
    }

    if (value.length == data.length) {
      r.push(value)
    }

    return r;
  }, [])
}

const result = cartesian(data);
console.log(result);

Answer №4

Take a look at this sequential method. Go through an array of arrays and update the items in the output one by one.

const information = [
  ["x", "y"],
  ["z", "w"],
  ["m", "n"]
];

let result = [""];
information.forEach(arr => {
  const temporary = [];
  arr.forEach(item => result.forEach(curr => temporary.push(`${curr}${item}`)));
  result = [...temporary];
});

console.log(result);

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

Utilizing Vue.js with Firestore: Retrieve information from Firestore without rendering any data on the screen

When attempting to display my data from Firestore, I encountered an issue where the data was retrieved successfully when hovering over the <td> tag but not actually displayed. Here is my file for fetching data from Firestore: <template> & ...

Manipulate Browser Navigation Behavior using JavaScript or AngularJS

How to Manage Browser Back Button Behavior Using AngularJS or JavaScript This is not a question, but rather a demonstration of how you can disable and manipulate the behavior of the browser's back button when using AngularJS or plain JavaScript. ...

Optimal method for implementing $scope.$apply(); or $scope in scenarios outside of Angular when working with Angular Components

As outlined in Kendo's best practices, there are instances where Kendo necessitates the use of $scope.$apply(); to update Angular. However, with the emergence of the new AngularJS 1.5 component, it is advised against relying on $scope. The code for t ...

Creating a PDF document with multiple pages using a PHP loop, integrating with AJAX, and utilizing the m

Looking for assistance with a plugin development project involving PDF generation using AJAX. The challenge lies in generating multiple PDFs for each user within a loop. The goal is to create PDFs with multiple pages for individual users. If that's n ...

Using the spread operator in combination with the reduce function in JavaScript

I am attempting to generate all possible paths of the provided JSON object. I have managed to generate the paths, but I would like the final array to be flattened without any nested arrays inside it. I tried spreading the array, but there are still some ne ...

Exploring Typescript: Combining types (rather than intersecting them)

Let's analyze the scenario below type MergeFn = <K1 extends string, V1, K2 extends string, V2>( k1: K1, v1: V1, k2: K2, v2: V2 ) => ??? let mergeFn: MergeFn // actual implementation doesn't matter for this question What should b ...

AJAX response for form validation

I need to validate my contact form when the submit button is clicked. If all fields are valid, I want to display a Processing message using AJAX, followed by a success message with the entered name. The content of my Form is: <form onsubmit="return va ...

Failure of jQuery Code Upon Successful Execution

I'm having an issue with my jQuery ajax code. It's functioning perfectly, but I can't seem to get it to change the class of the button that triggers the event when it is successful. The code under success: does not seem to be working as inte ...

Ensuring that the initial column of a table remains in place while scrolling horizontally

Thank you for taking the time to read this. I am currently working on a table within a div container (div0) where the data is dynamically generated, resulting in a table with unpredictable height and width. The outer div allows for both vertical and horizo ...

Using JavaScript, include a child class into a parent class

I am facing an issue with my class hierarchy, which includes classes like Parent, Child1 (which extends Parent), and Child2. Parent contains an array of child items, but importing Child1 and Child2 into Parent leads to circular dependencies and errors whe ...

Is it possible to dynamically load an npm package based on the user's browser?

My current goal is to utilize the ResizeObserver Polyfill specifically for Edge browsers. I noticed the concept of ponyfill in the npm package documentation. Would I need to develop my own ponyfill, or is there an alternative approach that could be consi ...

Switching between Login Form and Register Form in VueJS template

Recently, I attempted to switch between the 'Login Form' and 'Register Form' using code that I found on codepen Flat HTML5/CSS3 Login Form. While the code functioned properly on its own, when integrated into a Vue Template, the form fai ...

Is MongoDB still displaying results when the filter is set to false?

I am currently trying to retrieve data using specific filters. The condition is that if the timestamp falls between 08:00:00 and 16:00:00 for a particular date, it should return results. The filter for $gte than 16:00:00 is working correctly, but the $lte ...

modification of class into hooks, receiving error message 'then' property is not found in type '(dispatch: any) => Promise<void>'

As a newcomer to React hooks, I have been converting code from class components to hooks. However, I am encountering an error message when trying to use 'then' in hooks that says 'Property 'then' does not exist on type '(dispa ...

Can you explain the meaning of '<Hero[]>' in programming jargon?

Hello there! I am new to learning angular and typescript, and currently going through a tutorial at angular. However, I stumbled upon something that I find confusing. For example: 1. getHeroes(): Observable<Hero[]> { this.messageService.add(&ap ...

The CSS root variable is failing to have an impact on the HTML element's value

I'm in the process of changing the text color on home.html. I've defined the color property in a :root variable, but for some reason, it's not appearing correctly on the HTML page. Take a look at my code: home.scss :root { --prim-headclr : ...

Experience some issues with the NextJS beta app router where the GET request fails when using fetch, but surprisingly works

Having an issue with a GET request while using NextJS with the APP dir... The function to getProjects from /project route.ts is not triggering properly. console.log("in GET /projects") is never triggered, resulting in an unexpected end of JSON ...

What could be the reason for typescript not issuing a warning regarding the return type in this specific function?

For instance, there is an onClick event handler attached to a <div> element. The handler function is supposed to return a value of type React.MouseEventHandler<HTMLDivElement> | undefined. Surprisingly, even if I return a boolean value of fal ...

What is the best way to choose a date and time in a custom format within my React application?

I'm currently developing the front-end of my application using React. I am looking for a way to capture the date and time in the specific format shown in this image. Any suggestions or solutions would be greatly appreciated! ...

The RC-dock library's 'DockLayout' is not compatible with JSX components. The instance type 'DockLayout' is not a valid JSX element and cannot be used as such

Despite encountering similar questions, none of the provided answers seem to address the issue within my codebase. My project utilizes React 17, Mui v5, and TS v4. I attempted to integrate a basic component from an external package called rc-dock. I simply ...