Combining string values from arrays of varying lengths in JavaScript

Here are two arrays I am working with:

The first array (Array1) contains the elements:

arr1 = ["Precon", "Contra", "Postco", "Cancel", "Consul"]

The second array (Array2) contains the elements:

arr2 = ["EJID", "EMBA", "EMPR", "GOBI", "PART", "PPOL", "SACI", "SOFL", "SOFM", "0000", "", "0002", "0003", "0004", "0005", "0006", "0007", "0008", "0009", "0010", "0011", "0012", "0013", "0014", "0015", "0016", "011", "0110", "9999"]

I am looking to create a new array by combining each element from Array1 with all elements from Array2, resulting in a final array like this:

final = ['Precon-EJID', 'Contra-EJID', 'Postco-EJID', 'Cancel-EJID', 'Consul-EJID', 'Precon-EMBA', 'Contra-EMBA', 'Postco-EMBA', 'Cancel-EMBA', 'Consul-EMBA', 'Precon-EMPR', 'Contra-EMPR', 'Postco-EMPR', 'Cancel-EMPR', 'Consul-EMPR'...etc]

Thank you for your help!

Answer №1

To achieve this, you can utilize 2 straightforward for of loops:

var arr1 = ["Precon", "Contra", "Postco", "Cancel", "Consul"];

var arr2 = ["EJID", "EMBA", "EMPR", "GOBI", "PART", "PPOL", "SACI", "SOFL", "SOFM", "0000", "", "0002", "0003", "0004", "0005", "0006", "0007", "0008", "0009", "0010", "0011", "0012", "0013", "0014", "0015", "0016", "011", "0110", "9999"]

var finalArr = [];

for ( var item2 of arr2 ) {
  for ( var item1 of arr1 ) {
    finalArr.push(`${item1}-${item2}`);
  }
}

console.log(finalArr);

Answer №2

To combine two arrays, you can utilize nested Array#map functions and then flatten the results by using Array#concat:

const arr1 = ["Precon", "Contra", "Postco", "Cancel", "Consul"]

const arr2 = ["EJID", "EMBA", "EMPR", "GOBI", "PART", "PPOL", "SACI", "SOFL", "SOFM", "0000", "", "0002", "0003", "0004", "0005", "0006", "0007", "0008", "0009", "0010", "0011", "0012", "0013", "0014", "0015", "0016", "011", "0110", "9999"]

const result = [].concat(...arr2.map((s1) => arr1.map((s2) => `${s2}-${s1}`)))

console.log(result)

Answer №3

Here's a simple solution in just one line:

arr1 = ["Precon", "Contra", "Postco", "Cancel", "Consul"]
arr2 = ["EJID", "EMBA", "EMPR", "GOBI", "PART", "PPOL", "SACI", "SOFL", "SOFM", "0000", "", "0002", "0003", "0004", "0005", "0006", "0007", "0008", "0009", "0010", "0011", "0012", "0013", "0014", "0015", "0016", "011", "0110", "9999"]

const result = [].concat(...arr1.map(prefix => arr2.map(suffix => prefix+suffix)));
console.log(result)

// NOTE: To maintain order, simply switch the positions of arr1 and arr2:

const orderedResult = [].concat(...arr2.map(suffix => arr1.map(prefix => prefix+suffix)));
console.log(orderedResult)

Answer №4

const prefixes = [
  "Precon",
  "Contra",
  "Postco",
  "Cancel",
  "Consul"
];

const suffixes = [
  "EJID", "EMBA", "EMPR",
  "GOBI", "PART", "PPOL",
  "SACI", "SOFL", "SOFM",
  "0000", "", "0002",
  "0003", "0004", "0005",
  "0006", "0007", "0008",
  "0009", "0010", "0011",
  "0012", "0013", "0014",
  "0015", "0016", "011",
  "0110", "9999"
];

const results = suffixes
  .map(suffix => prefixes.map(prefix => prefix + '-' + suffix))
  .reduce((xs, ys) => [...xs, ...ys]);

console.log(results);

Answer №5

One alternative is to utilize the reduce method...

let arr1 = ["Precon", "Contra", "Postco", "Cancel", "Consul"]

let arr2 = ["EJID", "EMBA", "EMPR", "GOBI", "PART", "PPOL", "SACI", "SOFL", "SOFM", "0000", "", "0002", "0003", "0004", "0005", "0006", "0007", "0008", "0009", "0010", "0011", "0012", "0013", "0014", "0015", "0016", "011", "0110", "9999"]

let arr3 = arr2.reduce((arr, val) => {
    let f = []
    arr1.forEach(itm => val && f.push(itm + '-' + val))
    return arr.concat(f)
}, [])

console.log(arr3)

Answer №6

Presenting a fun and challenging recursive solution, just as requested by the original poster. It definitely took some time to figure this one out! 😄

arr1 = ["Precon", "Contra", "Postco", "Cancel", "Consul"]

arr2 = ["EJID", "EMBA", "EMPR", "GOBI", "PART", "PPOL", "SACI", "SOFL", "SOFM", "0000", "", "0002", "0003", "0004", "0005", "0006", "0007", "0008", "0009", "0010", "0011", "0012", "0013", "0014", "0015", "0016", "011", "0110", "9999"]

var arr = [];

console.log(concat(arr1, arr2, 0, 0, 0));

function concat(arr1, arr2, arrIndex, index1, index2) {
  //console.log(arr1.length);
  if (index2 === (arr2.length)) {
    return;
  } else {
    arr[arrIndex] = arr1[index1] + '-' + arr2[index2];
    if (index1 !== (arr1.length - 1)) {
      index1++;
    } else if (index1 === (arr1.length - 1)) {
      index1 = 0;
      index2++;
      //concat(arr1, arr2, ++arrIndex, index1, index2++); // Not here dummy :P
    }
    concat(arr1, arr2, ++arrIndex, index1, index2++);
  }
  return arr;
}

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

The drop-down menu remains visible even after clicking outside of it

I've written a script that works when clicked, but it doesn't hide when clicked outside of it. $(document).ready(function() { //Translate(); //caling Language Translater function $("#translate_image").attr('href', base_url) ...

The JS slider fails to function properly following the migration of AngularJS from version 1.0.8 to 1.2

Seeking assistance with migrating AngularJS from version 1.0.8 to 1.2 and encountering issues with a JavaScript slider that is no longer functioning post-migration... After upgrading to 1.2, added the angular-route.js library and injected 'ngRoute&ap ...

Creating a new object by extracting various properties from an array of objects using Javascript

Trying to achieve the following: I possess an array of objects , var arr = [ { key: "aabFaa", text: "aabFaa" ,field: "firstName",checked: true}, { key: "aAaaaa", text: "aAaaaa", field: "firstName", checked: true }, ]; I aim to extract the "text" an ...

issue with splice function

I have a JavaScript function that is supposed to collect all input values from text boxes and store them in an array. However, I want to remove any input value with the type "button" from the array before proceeding. Here is the code snippet: <!-- lang ...

Different techniques for using percentages in CSS transformations to create dynamic animations for DOM element translations

I have 14 objects positioned across the dom that I need to animate using the translate property. Currently, I am using transform: translate(x%, y%) for each object, requiring me to calculate the translation amount and apply a CSS style individually. This m ...

The Jquery ajax page is redirecting automatically when a post request is made

Encountering an issue while attempting to upload multiple files through AJAX, as the process redirects to a blank page displaying only the names of the uploaded files. Here is the HTML tag: Below is the JavaScript function: function upload(){ var proje ...

Efficiently finding elements in a PHP array

I am facing a challenge with an array containing approximately 3500 array items. The structure of the array is provided below. Within this array, I have two dynamic variables that change frequently and I need to search for the row price_value based on alre ...

Combining two indexes into a single index within a QByteArray using the QT framework

My QByteArray holds data structured as follows: [0] --> A [1] --> B [2] --> C [3] --> D I am looking to combine pairs of elements like so: [0] --> AB [1] --> CD Is this achievable, and if so, how can I accomplish it? Thank you. ...

Ways to activate a click event on a parent div without affecting a particular child element in Angular

I am working on an Angular component that consists of nested div elements. My goal is to trigger a click event on the parent div, however, I want to ensure that if the menu child div is clicked, the parent div's click event should not be triggered. C ...

Is there a way to conceal the text box in jquery during the initial loading phase?

I have encountered an issue while working on a project. My code only functions properly when I click after it has loaded. I have assigned IDs to each user and implemented code for toggling active/inactive users by passing the ID to each textbox and span el ...

Improving the performance of HTTP requests and dividing a CSV file into multiple parts

Currently, I am attempting to retrieve data from a CSV file on a website. My approach involves initially splitting the string by line breaks ('\n') and then again by commas (','). However, when I attempt to print the content of one ...

Dialog box for confirmation/Alert box for SweetAlert before sending Ajax POST request

One issue I am encountering is with an Ajax POST function that submits a form. In the beforeSend() function, there is a sweetAlert dialog that prompts the user to either abort or continue the Ajax POST call. The problem arises when the success function tri ...

The custom tooltips feature in Google linecharts will function properly only when the focus target is set to category

I am currently using PHP, MongoDB, and JavaScript to develop my Google Charts Line charts. In PHP, I have designated one column as the tooltip role, positioned as the last but one column. The default tooltip displays the X-axis (Date) and Y-axis (Value), b ...

Ensure that the content-length header is properly set for each section of a multipart/form-data upload

I am looking to send a post request with multiple files using the multipart/form-data type. It's important for me to know the file size (content-length) of each file on the server side. When constructing the POST request in Javascript, I utilize a Fo ...

Press a button to generate an image inside a specified div element

I've been struggling with this particular issue and have attempted various solutions, but there seems to be an error in my implementation as it's not functioning correctly. My goal is simple: I want to be able to click a button and have an image ...

gulp-watch does not monitor files that are newly created or deleted

Currently working on a task: gulp.task('assetsInject', function () { gulp.src(paths.index) .pipe(plugins.inject( gulp.src(paths.scripts, {read: false}), { addRootSlash: false } ...

Mastering the art of customizing classes and styles in material-ui (React)

I am facing a challenge with version 1.2.1 of material-ui. My goal is to make the AppBar component transparent by overriding its styles as per the documentation here. This is the code snippet I have been working on: import React, { Component } from ' ...

The color type input is not responding to the onChange event

I have been searching a lot and exploring answers on Stack Overflow, yet I have had no luck. I am trying to retrieve the color value when the color is changed in an input field. Here is the code I am using, could you please assist me in finding out why it ...

Executing multiple nested $http calls in Angular can significantly slow down the process

Within my angular application, I am currently dealing with 6 to 7 http chaining requests that are taking a significant amount of time to execute. What are some strategies for optimizing this process? empSvc.getallEmp().then(function (data) { if (dat ...

Exploring depths of data with AngularJS: multiple levels of drilling

I am new to AngularJs and facing a challenge with a complex JSON structure that I need to use for an auto complete feature. I want to create an auto complete for only the child elements within the structure, without displaying the parent categories. Acce ...