Changing an array into an object while also keeping track of duplicate occurrences in JavaScript

Can someone assist me with transforming an array into an object and counting the duplicates of each size? I am hoping to achieve a result like this:

{
    "BLACK": {
    "XXS": 1,
    "M": 1,
    "L": 1,
    "XL": 2 "},
    "WHITE": {
    "XXS": 1,
    ...
}

I attempted to solve this using reduce and split, but the outcome was not as expected:

const products = ["black-XXS", "black-M", "black-L", "black-XL", "black-XL", "white-XXS", "white-L", "red-M "," blue-2XL "," blue-2XL "," blue-2XL "]

var result = products.reduce ((prev, cur) => {
    color = cur.split ("-") [0]
    size = cur.split ("-") [1]

    // prev [size] = (prev [size] || 0) + 1
    previous [color] = {[size]: ([size] || 0) + 1}
    // prev [color] = {[size]: (prev [size] || 0) + 1}
    // {[color] = {[size]: ([size] || 0) + 1}}

    // console.log (previous)
    return prev;
}, {});

Result = {"black": {"XL": "XL1"}, "white": {"L": "L1"}, "red": {"M": "M1"}, "blue": { "2XL": "2XL1"}}

Answer №1

To ensure the outer object exists, make sure to create it first before proceeding to increment the size property:

const items = ["blue-M", "red-S", "green-L", "yellow-XL", "purple-XXS"];

const itemsByColor = {};
for (const item of items) {
  const [color, size] = item.toUpperCase().split('-');
  if (!itemsByColor[color]) {
    itemsByColor[color] = {};
  }
  itemsByColor[color][size] = (itemsByColor[color][size] || 0) + 1;
}
console.log(itemsByColor);

Answer №2

My approach differed slightly, but I agree with CertainPerformance's suggestion to start by defining your empty Object first. It's also important to ensure that every element in your array follows a consistent format. For instance, there are white spaces within the " blue-2XL " string.

Here is my solution:

const products = ["black-XXS", "black-M", "black-L", "black-XL", "black-XL", "white-XXS", "white-L", "red-M", "blue-2XL", "blue-2XL", "blue-2XL"]

const hash = {};
products.forEach(item => {
    let color = item.split("-")[0];
    let size = item.split("-")[1];
    if(!hash[color]) {hash[color] = {}};
    if(!hash[color][size]) {hash[color][size] = 1} else {hash[color][size] = hash[color][size] + 1};
});

If you console.log(hash);, you should see:

{ black: { XXS: 1, M: 1, L: 1, XL: 2 },
white: { XXS: 1, L: 1 },
red: { M: 1 },
blue: { '2XL': 3 } }

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

Display a Button exclusively at the bottom row of a Table using just Javascript

I am currently working on a 4-column table with a "+" button in the last column. This button's purpose is to add an additional column when clicked. However, the button is appearing in all rows of the table, and I would like it to be displayed only in ...

JavaScript code to toggle the navigation bar on mobile devices

I am experiencing an issue with a script that is not performing the desired task. I am looking for a script that can add the Class "active" to a ul element with the id "btnMob0". Currently, my script looks like this: <script type="text/javascript"> ...

Displaying and Concealing Table Rows using Javascript

I am working with an array of prices that are being displayed in a table using a foreach loop. The goal is to hide specific rows in the table based on certain conditions. The $status variable is set to "YES" if the price is => 30, and "NO" if the price ...

Retrieving two sets of AJAX data at the same time

Recently, I've encountered a challenge with filling in data from a MySQL server via PHP into two tables in my HTML. As someone new to website development, I might not be articulating the issue correctly. In my HTML, I've included my external .js ...

Whenever I try to modify the capitalization of the input word, an error always pops up. I attempted to utilize toLowerCase() to no avail

const selectUserSelection = (choice=choice.toLowerCase()) => { if (choice === 'rock' || choice === 'paper' || choice === 'scissors') { return choice; } else { console.log('Invalid choice entered!'); ...

How can we effectively share code between server-side and client-side in Isomorphic ReactJS applications?

For a small test, I am using express.js and react.js. Below you can find my react code: views/Todo.jsx, var React = require('react'); var TodoApp = React.createClass({ getInitialState: function() { return { counter: 0 ...

When utilizing $resource, Protractor experiences a timeout while trying to synchronize with the page

Currently, I am testing Protractor with a small AngularJS application. Here is the test scenario: describe('Testing Protractor', function() { var draftList; it('should count the number of drafts', function() { browser.get(&ap ...

Is it possible to use a String as an index array key in Java? For example, can you do something like `array["a"] =

Is it possible for Java to utilize a String as an index array key? For instance: array["a"] = 1; ...

Sending information from a Bootstrap modal form

I'm experiencing an issue with my form that triggers a modal for confirmation before submission. The modal contains the submit button and is located outside of the <form> tag. Surprisingly, it works perfectly fine on all browsers except for Inte ...

Tips for dynamically loading fresh Google Adsense code with JavaScript without any user interaction

Recently, Google made a change in their ad code by replacing <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js</script> with <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygo ...

Tips for extracting URL parameter values in React applications

Here is a component that allows for searching: import { ChangeEvent, useCallback, useState } from 'react'; export function SearchComponent() { const [searchValue, setSearchValue] = useState<string>(''); const updateSearchValu ...

The cause of Interface A improperly extending Interface B errors in Typescript

Why does extending an interface by adding more properties make it non-assignable to a function accepting the base interface type? Shouldn't the overriding interface always have the properties that the function expects from the Base interface type? Th ...

Discover how to use jQuery to add CSS styles to every span element on a

I'm currently using JavaScript and jQuery to create a tree structure in ASP.NET MVC. There's an 'add' button that will add siblings and child nodes at the same level. To determine the appropriate action, I have implemented the followi ...

Switch to a new section element every 20 seconds

After conducting research, I discovered that my initial approach to this task is not feasible. I have two elements on a page: a graph created using the chart.js framework and a data table. The data in the chart only changes once a day, and the data retriev ...

Tips for simultaneously indexing multiple properties on a JavaScript object

Imagine having a JavaScript object structured like this: var x = { 'one': 1, 'two': 2, 'three': 3 } Now, suppose you have an array containing the specific keys you want to access from this object. Here are the keys you ...

Looking to incorporate an Ajax feature that allows for updating dropdown menus in each row of the database

Please find below the UI screenshot highlighting the dropdown menu: What I am looking for? I would like the option selected in the dropdown menu to be updated for each specific row in the database using AJAX. Below are the codes I have written. As a beg ...

Does anyone know how to designate a Thumbnail when playing Audio on iOS Safari?

I recently launched a website to showcase my new podcast. The audio is embedded in a media player on the page, and when it's playing, it shows up on the Control Center audio tab and even on the lock screen. However, the thumbnail displayed is just a ...

Creating visualizations with varying array lengths on a single Pandas plot

a and b represent the datetime indexes for two sets of values, A Values and B Values, respectively. The size of A Values is larger than that of B Values. I am looking to create a code snippet where both sets are plotted on the same graph with numpy arrays ...

What is the minimum number of lines that can be used for javascript code?

Currently, I am in the process of developing a custom JavaScript minifier. One question that has come up is whether it is necessary to insert line breaks after a certain number of characters on a single line, or if it even makes a difference at all? For i ...

Quickest method for merging elements from a single numpy array into specific indices of a 2D numpy array

I am looking for an efficient solution to add the contents of numpy arrays to a 2D array starting from specific row indices. Instead of looping through the arrays, I need a faster method to handle this operation across multiple samples. In [1]: A = np.zer ...