Tips for obtaining the combined outcome of multiple arrays (3 to 5 arrays) in JavaScript

How can we transform an array of objects with nested arrays into a new array of objects with mixed values?

Consider the following input:

var all = [
  {
    name: "size",
    value: [20, 10, 5],
  },
  {
    name: "color",
    value: ["red", "black"],
  },
  {
    name: "width",
    value: [500, 600],
  },
];

The desired output should be like this:

var output = [
  { size: 20, color: "red", width: 500 },
  { size: 20, color: "red", width: 600 },
  { size: 20, color: "black", width: 500 },
  { size: 20, color: "black", width: 600 },
  { size: 10, color: "red", width: 500 },
  { size: 10, color: "red", width: 600 },
  { size: 10, color: "black", width: 500 },
  { size: 10, color: "black", width: 600 },
  { size: 5, color: "red", width: 500 },
  { size: 5, color: "red", width: 600 },
  { size: 5, color: "black", width: 500 },
  { size: 5, color: "black", width: 600 },
];

Answer №1

it seems like a recursive challenge:

const allValues = 
  [ { label: 'size',  values: [ 20, 10, 5]      } 
  , { label: 'color', values: [ 'red', 'black'] } 
  , { label: 'width', values: [ 500, 600]       } 
  ] 

const result = []

function arrangeValues (array, index, currentItem)
  {
  if (index < array.length)
    {
    array[index].values.forEach( value =>
      {
      let obj = Object.assign( {}, currentItem,{ [array[index].label]: value} ) 
      arrangeValues(array, index+1, obj)
      })
    }
  else
    result.push(currentItem)
  }

arrangeValues(allValues, 0, {})

console.log( result )
.as-console-wrapper { max-height: 100% !important; top: 0 }

optimized code for clearer implementation

const allValues = 
  [ { label: 'size',  values: [ 20, 10, 5]      } 
  , { label: 'color', values: [ 'red', 'black'] } 
  , { label: 'width', values: [ 500, 600]       } 
  ] 

const output = generateArrangement( allValues )

console.log( output )

function generateArrangement( array )
  {
  const
    resultSet = []
  , arrayLength = array.length
    ;
  aggregateValues(0, {})
  return resultSet

  function aggregateValues(index, tempItem)
    {
    if (index < arrayLength)
      array[index].values.forEach( val =>
        aggregateValues( index + 1, Object.assign( {}, tempItem, { [array[index].label]: val} )))
    else 
      resultSet.push(tempItem)
    }
  }
.as-console-wrapper { max-height: 100% !important; top: 0 }

Answer №2

For those websites or applications that are compatible with ES6, combining arrays can be achieved effortlessly by utilizing the spread operator:

const mergedArray = [...arrayOne, ...arrayTwo, ...arrayThree];

If ES6 is not supported, an alternative approach using concat() can still get the job done:

var mergedArray = arrayOne.concat(arrayTwo).concat(arrayThree)

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 makes it easy to streamline conditions

Can someone help me simplify this repetitive condition? if (this.get('fileUrl')) { const isUnsplash = this.get('fileContainer.asset_kind') === 'UnsplashAsset'; return Asset.create({ url: this.get('f ...

When querying the model, the result may be undefined

I'm encountering an issue where I can't access the content of an array of documents in my model and it's returning undefined. Here is the model structure (Project.js): var mongoose = require('moongoose'); var Schema = mongo ...

encountering an issue with server-side rendering of React causing an error

Node.js has been a bit of a challenge for me, especially when it comes to working with react and express. I have been struggling to find comprehensive tutorials and troubleshooting resources, leading me to ask minimal questions in the correct manner. While ...

Associate the right-click action with Angular Material

I'm currently working with Angular Material. My goal is to develop a directive that allows me to trigger a right-click event on an element. This is what I have attempted so far: JavaScript: app.directive('rightClick', ["$parse", function ...

Is there a way to specify object keys in alignment with a specific pattern that allows for a variety of different combinations

I am seeking a way to restrict an object to only contain keys that adhere to a specific pattern. The pattern I require is: "{integer}a+{integer}c". An example of how it would be structured is as follows: { "2a+1c": { // ... } } Is there a ...

Switch between classes when hovering over / exiting ngFor elements

Displayed below is an element created using ngFor <span *ngFor="let picture of pictures; let i = index"> <a target="_blank" href="{{picture.image}}" class="thumbnail-display image-overlay"> <span class="overlay-icon hide"> ...

Having trouble with MUI auto import suggestions in my Next.js 13 project on VS Code

I'm currently developing a project using Next.js 13 and have installed MUI. However, I am encountering an issue where VS Code is not providing auto imports from the @mui/material library, as shown in the attached screenshot. https://i.stack.imgur.com ...

'Error: Object does not have access to the specified property or method 'values'

I've been working on writing some code to retrieve and read a JSON file. It seems to work fine in Chrome, but I'm running into issues with IE11, which is the browser I need to use. I've tried changing variable names, but the problem persists ...

Switch out HTML dynamically using JavaScript/JQuery, embracing the principles of DRY coding

As a newcomer to front-end development, one issue I frequently encounter is avoiding repetition when dynamically generating HTML using JS/jQuery. Imagine you have a DOM object that has various states. Typically, all you need to do with JS is switch betwee ...

"Implementing automated default values for Select/dropdown lists in ReactJs, with the added capability to manually revert back to the default selection

After browsing multiple websites, I couldn't find a clear solution on how to both set and select a default value in a select element. Most resources only explain how to set the value, without addressing how to reselect the default value. My Requireme ...

What is the best way to send a prop to my home route following a redirect?

I am working with react-router-dom and I want to pass :id to my first route (/) when redirecting. This is important so that I can access :id in my Interface component and maintain consistent URL structure for my single-page application. Is it feasible to a ...

Whenever I attempt to include state in a React class that is declared as a constant, I consistently encounter the error message: "TypeError:

Apologies for the redundancy, but as a newcomer to React, I previously inquired about a similar issue and have since modified my code. My current challenge involves trying to access a state value within a const React class. Below is the excerpt from my Ar ...

Using Vue.js to dynamically append router links with JavaScript

let link = `<router-link :to="{name : 'profile' , params : { slug : ${response.data.nickname} }}"> <img src="${response.data.avatar}" class="card__image"> </router-link>`; $('body').appen ...

Validating classes in Node.js using class-validator

I'm having some trouble with the class-validator package in my Node project. It's not being recognized and throwing an error. @MinLength(10, { ^ SyntaxError: Invalid or unexpected token Here's an example of what I'm doing: co ...

Is it possible to transfer files using web-bluetooth technology?

As I work on developing an embedded system that counts the number of cars, saves their speed and time data in a logs file using rsyslog. Simultaneously, I am creating a web-API (in Typescript/Angular with Electron for Desktop usage and later Web as well) t ...

Leveraging deferred for linking loops involving several ajax requests

Despite the fact that several questions have been answered on this topic, none of them seem to be effective in this particular scenario. function login(u,p) { console.log(1); return $.post(url, {u,p}); } function out() { console.log(3); //a f ...

How can we use the useState hook in React to dynamically generate state variables?

I'm currently working on a React app where input fields need to be stored in the state. While I can use the useState hook to easily store these values, the challenge I'm facing is that I don't know what fields are needed since they are retri ...

Issues encountered while trying to access a child state using Ionic and UI-Router

My current setup includes the following parent states: // Abstract state for tabs directive .state('tab', { url: "/tab", abstract: true, templateUrl: "templates/tabs.html", controller: "TabCtrl" }) // Each tab has its ow ...

What common problems arise from using mutable data types in a single-threaded environment?

In JavaScript, concurrency is modeled by an event loop, eliminating race conditions. Given this, what are the potential downsides of performing a type-safe operation in the main scope of a program that would warrant caution? const m = new Map([["foo", tru ...

What is the best way to utilize "exports" in package.json for TypeScript and nested submodules?

Looking to leverage the relatively new "exports" functionality in Node.js/package.json for the following setup: "exports": { ".": "./dist/index.js", "./foo": "./dist/path/to/foo.js" } so that ...