To modify a list

I'm facing a challenge where I need to restructure an array, but I'm not sure where to begin.

Here is the original array:

var products =
[
  "rose-S", 
  "rose-M", 
  "rose-L", 
  "rose-XL", 
  "rose-XL", 
  "blue-XS", 
  "blue-L", 
  "green-M"
]

The desired structure should be:

{ 
  "rose": { 
    "S": 1, 
    "M": 1, 
    "L": 1, 
    "XL": 2 
  }, 
  "blue": { 
    "XS": 1, 
    "L": 1 
  }, 
  "green": { 
    "M": 1 
  }, 
}

What are some steps I could take to achieve this restructuring?

Answer №1

Transform the array into an object structure by extracting and categorizing the items based on their color and size attributes. Ensure that a separate sub-object is created for each unique color, and within it, another level of objects for different sizes with a count of occurrences:

const products = ["rose-S","rose-M","rose-L","rose-XL","rose-XL","blue-XS","blue-L","green-M"]

const result = products.reduce((acc, item) => {
  const [color, size] = item.split('-') // obtain color and size information from each item
  
  if(!acc[color]) acc[color] = {} // create color object if it doesn't exist
  
  if(!acc[color][size]) acc[color][size] = 0 // set size sub-object if not already present
  
  acc[color][size] += 1 // increase count of current color/size combination

  return acc
}, {})

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

Tricky traversal of a sophisticated SimpleXMLElement structure

I am looking to extract and save certain values from XML data. First step - I begin by obtaining the XML structure: $xml = $dom_xml->saveXML(); $xml_ = new \SimpleXMLElement($xml); dd($xml_); Within this structure, the TextFrame element conta ...

Verify if uploading a photo is necessary

Here is my approach to ensuring that a file is added before it can be uploaded: <script type="text/javascript> function check(){ var elm = document.getElementById("hello-world"); if (elm.value.length > 0){ alert("Hey"); re ...

Using JavaScript to we can transfer the function result to an HTML input field

Is there a way to display the result of a JavaScript function in an HTML input field? Here is an example form: https://i.sstatic.net/HHHl2.png When I click "Run - Script," the following simple script is executed: <button type="submit" class="btn btn ...

AngularJS ng-repeat doesn't refresh following an Ajax request

I am using an AngularJS application where I have a chat feature on the right side for communication with my clients. Here is the HTML code: <div class="recent" ng-show="show_chat_list"> <h2></h2> <div ng-repeat="customer in r ...

Tips on employing the sendkeys function in selenium webdriverjs through promise chaining

Here is the coding snippet: driver.get(url).then(function(){ txtFnn = driver.findElement(webdriver.By.xpath(xpath)); return txtFnn; }).then(function(){ txtFnn.sendkeys("12345678"); }) Issue: An error occurred: Typ ...

Effortlessly fill dropdown menus with data from JSON files

I've been using this jQuery code successfully, but I recently needed to add 3 more field columns to the JSON. My goal is to have the HTML select drop-downs dynamically change based on the data from the previous drop-down. Additionally, my current jQue ...

Updating input value in React on change event

This is the code for my SearchForm.js, where the function handleKeywordsChange is responsible for managing changes in the input field for keywords. import React from 'react'; import ReactDOM from 'react-dom'; class SearchForm extends ...

Retrieve 2 values from a JSON array in a Node.js environment

Can someone assist me in extracting two values from my JSON array? Here is a link to the array: http://pastebin.com/tm5StsZ3 I am looking to retrieve both an ID and a key from these arrays. Any help would be greatly appreciated. I am currently working wit ...

Encountering a tucked-away issue with the Safari scroll bar?

Encountered an interesting bug where users are unable to scroll down a text nested inside a div. This issue seems to be isolated to Safari, as it doesn't occur in other browsers. I have prepared a sample file to demonstrate the bug and would apprecia ...

Confirm the input validity using jQuery for radio buttons, checkboxes, and dropdown menus

When it comes to validating input fields like text, email, radio, checkbox, and select, I have the following structure in my form: <fieldset> <div class="form-top"> <div class="form-bottom"> <div class="for ...

Encountering an issue with resolving a local variable during the execution of a test with Protractor

I'm currently learning about async calls in protractor as a newbie to the tool. I am struggling to figure out how to handle a boolean variable that I set to true if any test case fails and the execution goes to the catch block for a promise. Below is ...

Indication of a blank tab being displayed

I'm struggling to get my Angular directives working in my project. I've tried implementing a basic one, but for some reason it's not showing anything on the screen. Can anyone help me troubleshoot this issue? Here is my JS code: angular ...

The error message stating that an arrow function is expected after declaring this type parameter

Encountered an error when trying to start the project with yarn start: $ yarn start yarn run v1.22.17 $ run-s build exec $ babel src/ -d lib/ SyntaxError: .../src/App.js: Expected an arrow function after this type parameter declaration. (8:9) 6 | 7 ...

Repositioning a variable number of divs as the cursor hovers over the target area

Can anyone show me how to generate div elements in a loop using jQuery and change their position with the "mouseover" function? I've tried some code, but the positioning isn't changing correctly. Any suggestions on what needs fixing? var r, g, ...

Error: Unable to assign property '_id' to a string

I'm currently working on a basic REST API that includes an endpoint for posting data to be saved in MongoDB from an external API. Here's the code I've written so far: app.post('/data', (req, res) => { let url = 'https ...

Prevent the default submission of the form while still allowing the browser's autocomplete feature to function

I need to send form data using ajax and want to prevent the default browser behavior by using preventDefault(). However, I still want the browser to remember the data for future autocompletion. Is there a way to achieve this? HTML <form id="form-login ...

Husky 5: The Ultimate Gitignore Manager

Last week, a new version of Husky was released, known as Husky 5. I came across an interesting article discussing the features and updates in this release that can be found here. Upon migrating to Husky 5 (), I discovered a new directory named .husky with ...

Display a text field upon clicking on a specific link

I am trying to create a text field that appears when a link is clicked, but I haven't been able to get it right yet. Here is what I have attempted: <span id="location_field_index"> <a href="javascript:void(0)" onclick="innerHTML=\"< ...

Extracting portions of a string using the "sscanf" function in the C programming language

I have a GPS string that looks like this: char gps_string[] = "$GPRMC,080117.000,A,4055.1708,N,02918.9336,E,0.00,316.26,00,,,A*78"; I am trying to extract the substrings between the commas in the following sequence: $GPRMC 080117.000 A 4055.1708 . . . ...

Unlimited scrolling gallery with multiple rows

I am looking for a way to create a multi-row infinite loop scrolling gallery using html, css, and javascript. Can anyone help me with this? ...