Spread out, blend, combine... array with additional arrays

Explaining my problem may be a bit tricky due to my limited proficiency in English. I am currently working on an app using Angular.js, so our discussion will revolve around Javascript.

Imagine we have 2 arrays structured like this:

[
    [
      "Item 1",
      "Item 2"
    ],
    [
     "Item A",
     "Item B",
     "Item C"
    ]
]

My goal is to generate something along these lines:

[
  "Item 1 Item A",
  "Item 1 Item B",
  "Item 1 Item C",
  "Item 2 Item A",
  "Item 2 Item B",
  "Item 2 Item C"
]

The challenge arises when there are multiple arrays (3, 4, 5...) and the number of items in each array varies. The ultimate objective is to concatenate every item with all the others only once. Does anyone have any suggestions?

I have experimented with angular.forEach, for loops, among other techniques, but I am yet to discover a workable solution...

Answer №1

If you're looking for a solution, consider the following:

[
  ["First Item", "Second Item"],
  ["Item X", "Item Y", "Item Z"]
].reduce(function(primary, secondary) {
  var outcome = [];

  primary.forEach(function(itemOne) {
    var str = itemOne + ' ';

    secondary.forEach(function(itemTwo) {
      outcome.push(str + itemTwo);
    });
  });

  return outcome;
});


Here's the resulting output:

[
  "First Item Item X",
  "First Item Item Y",
  "First Item Item Z",
  "Second Item Item X",
  "Second Item Item Y",
  "Second Item Item Z"
]


Additional Update

For handling multiple arrays:

[
  ["Red", "Blue"],
  ["Cherry", "Grape", "Banana"],
  ["Quick", "Slow",]
].reduce(function(initialArray, newArray) {
  var outcome = [];

  initialArray.forEach(function(starting) {
    var str = starting + ' ';

    newArray.forEach(function(ending) {
      outcome.push(str + ending);
    });
  });

  return outcome;
});


The resulting combinations are as follows:

[
  // Red
  "Red Cherry Quick",
  "Red Cherry Slow",
  "Red Grape Quick",
  "Red Grape Slow",
  "Red Banana Quick",
  "Red Banana Slow",

  // Blue
  "Blue Cherry Quick",
  "Blue Cherry Slow",
  "Blue Grape Quick",
  "Blue Grape Slow",
  "Blue Banana Quick",
  "Blue Banana Slow"
]

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

Issue with ASP.NET Core Controller not properly receiving complete JavaScript array object from Ajax call

When passing a JavaScript Object Array through ajax to the controller, I noticed that if there are more than 11 objects in the array, the controller receives it as null. However, with 11 or fewer objects, the array is received successfully. Here is an exam ...

AngularJS url update event

In order to gather statistical data, I am interested in tracking how many times the URL has been changed. To achieve this, I have set up a counter that will increment each time the URL is modified. Does anyone have a solution for this? ...

Disabling a LinkButton within a GridViewclick using JavaScript on the Client Side

I am working with a GridView that includes a LinkButton control in one of the columns. I need to disable the click event from the client side based on certain conditions for this column. This means that for some rows, users should not be able to trigger th ...

Stopping a function when another function is invoked in JavaScript

I've been immersing myself in the search for a way to halt one function if another is called or triggered in JavaScript. Initially, I believed it to be unattainable, but I'm open to having my perspective changed. My current focus lies within a t ...

How can I apply a hover effect to images loaded through AJAX?

I am curious if it is achievable to incorporate a hover effect (animation) into content or images that are loaded via AJAX. Currently, I have the following code in place for this purpose, however, it seems to only work for images that are loaded without ...

Incorporating local JSON data into HTML: A Step-by-Step

I'm completely new to javascript and the utilization of json. What I want to accomplish is quite straightforward, although I am encountering difficulties. My objective is to create a website consisting of two pages: one that showcases artists and ano ...

What is the best way to incorporate a sleep function in JavaScript?

I am currently working on a game in html5 using javascript, and I am facing an issue with the sleep function. Specifically, I need to delay the execution of an isWin function for a few seconds before displaying a popup announcing that the player has won th ...

A step-by-step guide on extracting multiple data entries from JSON that correspond to an array of IDs

Within my JavaScript code, I am working with a JSON dataset containing posts, each with a unique post_id. I also have an array of specific post_ids that I want to use to extract certain posts from the main dataset. const dataset = [ {post_id: 1, titl ...

Is there a reason why this jquery is not functioning properly in Internet Explorer 8?

Seeking assistance to troubleshoot why this jQuery code is not functioning properly in IE8. It performs well in Chrome but encounters issues in IE. $(document).ready (function() { $('.first-p').hide(); $( "div.first" ).click(function() ...

Preserve a retrieved value from a promise in Angular

Upon loading the page, the dropdown menu is populated with various values (such as 1, 2...7). However, when attempting to set a specific value based on a certain condition within a promise, it doesn't seem to work. How can this issue be resolved? htm ...

Tips for modifying HTML elements using Javascript after a link is clicked

Imagine a scenario where there is a DIV called "videoplayer" containing an image within it. Is there a straightforward method to modify the HTML content inside this DIV when a link is clicked? For instance, the current content of the DIV is as follows: ...

What is the best way to include a variable or literal as a value in styled components?

When it comes to managing various use cases, I always rely on props. However, I am currently facing a challenge in changing the border color of a styled input during its focus state. Is there a way to utilize props for this specific scenario? Despite my f ...

Interacting with CouchDB using AJAX

Currently, I am creating a sample project using CouchDB. My plan is to develop a web application with AJAX and host it in the tomcat environment. I am interested in learning how to effectively communicate with the CouchDB server. While researching, I came ...

The data from the method in the Vue.js component is not displaying as expected

Currently diving into Vue.JS (2) and exploring the world of components. My current challenge involves using a component within another component, grabbing data from a data method. Here's what I have so far: HTML <div id="root"> <h1> ...

Transition smoothly with a fade-in effect as you scroll through the images, and proceed to

My Objectives: Implement a scrolling feature where images transition to the next one based on scroll movement. Create a cycle of images that automatically progress, with the view transitioning to the bottom section once all images are viewed. Currently f ...

Transmit parameters via onclick event on FullCalendar

I have been utilizing the full calendar feature and it's been functioning properly. However, I am encountering an issue with sending parameters via onclick event. Below is the JavaScript code that I currently have: <script> $(document).ready(fu ...

What are the solutions to the problems I am experiencing with Arrays in C?

One scenario involves passing an array to a function with its length determined by the user. #include<stdio.h> void mapper(int a[], int size); int main () { int n; printf("Please enter the number of inputs\n"); scanf("%d",&n); ...

Setting the default attribute to all tags in JavaScript using HTTP

I am currently learning HTML and trying to understand how things work... One thing I am struggling with is setting the target attribute for all links on my webpage so they open in a new tab... I have been experimenting with jQuery functions, but so far, ...

Converting Variable Values to Element IDs in JavaScript: A Helpful Guide

Is it possible to declare a value in variable A and then access that value as an id in variable B using the method getElementById()? var A = 10; var B = document.getElementById(A); console.log(B); ...

Calling the `firstValueFrom()` method in RxJS will keep the observable alive and not

Hey there, I'm currently having issues with using firstValueFrom(), lastValueForm(), and Observable.pipe(take(1)) in my TypeScript code with Angular 14 and RxJs 7.8.0. I am working with a Firebase server that provides stored image URLs via an API wit ...