What is the best approach to solving this problem using JavaScript?

My json file is filled with various types of beers, such as this example:

  {
    "type": "Unifiltered",
    "name": "Heineken Unfiltered",
    "id": "XY",
    "brand": "Heineken",
    "price": "1250",
    "alcohol": "0.04",
    "ingredients": [
      {
        "id": "XY2",
        "ratio": "0.15",
        "name": "salt"
      },
      {
        "id": "XY3",
        "ratio": "0.00",
        "name": "sugar"
      },
      {
        "id": "XY4",
        "ratio": "0.35",
        "name": "barley"
      }
    ],
    "isCan": false
  },

The challenge at hand involves categorizing these beers by their respective brands:

A friend of mine has a lengthy list of all the beers available in his establishment, a rather chaotic one at that. He wants to organize the beers according to their brand names. Additionally, he mentioned that the function should output an array consisting of Brand > objects containing arrays of Beers for each specific Brand.

For instance:

[{brand: Heineken, beers: [{...}, ...]}]""

Answer №1

const drinks = [{
    "type": "Unfiltered",
    "name": "Heineken Unfiltered",
    "id": "XY",
    "brand": "Heineken",
    "price": "1250",
    "alcohol": "0.04",
    "ingredients": [
      {
        "id": "XY2",
        "ratio": "0.15",
        "name": "salt"
      },
      {
        "id": "XY3",
        "ratio": "0.00",
        "name": "sugar"
      },
      {
        "id": "XY4",
        "ratio": "0.35",
        "name": "barley"
      }
    ],
    "isCan": false
},
{
    "type": "Type2",
    "name": "Name2",
    "id": "XY",
    "brand": "EFES",
    "price": "1250",
    "alcohol": "0.04",
    "ingredients": [
      {
        "id": "XY2",
        "ratio": "0.15",
        "name": "salt"
      },
      {
        "id": "XY3",
        "ratio": "0.00",
        "name": "sugar"
      },
      {
        "id": "XY4",
        "ratio": "0.35",
        "name": "barley"
      }
    ],
    "isCan": false
},
{
    "type": "Type3",
    "name": "Name3",
    "id": "XY",
    "brand": "EFES",
    "price": "1250",
    "alcohol": "0.04",
    "ingredients": [
      {
        "id": "XY2",
        "ratio": "0.15",
        "name": "salt"
      },
      {
        "id": "XY3",
        "ratio": "0.00",
        "name": "sugar"
      },
      {
        "id": "XY4",
        "ratio": "0.35",
        "name": "barley"
      }
    ],
    "isCan": false
  }];

var categorizedDrinks = drinks.reduce((categories, drink) => {
 categories[drink.brand] = [...categories[drink.brand] || [], drink];
 return categories;
}, {});

console.log("Categorized Drinks", categorizedDrinks);

It seems like a similar question has been answered here

let categorizedDrinks = drinks.reduce((categories, drink) => {
 categories[drink.brand] = [...categories[drink.brand] || [], drink];
 return categories;
}, {});
console.log("Categorized Drinks", categorizedDrinks);

Answer №2

Presented in a clear and easy-to-understand manner, utilizing the array.forEach() method instead of shorthand functions:

let drinks = [{
  "type": "Filtered",
  "name": "Budweiser Filtered",
  "id": "AB",
  "brand": "Budweiser",
  "price": "1000",
  "alcohol": "0.05",
  "ingredients": [
    {
      "id": "AB2",
      "ratio": "0.10",
      "name": "yeast"
    },
    {
      "id": "AB3",
      "ratio": "0.20",
      "name": "water"
    },
    {
      "id": "AB4",
      "ratio": "0.30",
      "name": "hops"
    }
  ],
  "isCan": true
}];

let companies = [];

// Iterate through all drinks
drinks.forEach((drink) => {
  // Check if the drink brand already exists in the list of companies
  let company = companies.filter((company) => company.brand === drink.brand)[0];
  
  if(company) {
    // If it does, add the drink to the drinks property of that brand
    company.drinks.push(drink);
  } else {
    // If not, create a new company with the drink and add it to the companies list
    company = {
      brand: drink.brand,
      drinks: [drink]
    }
    companies.push(company);
  }
});

console.log(companies);

Answer №3

In my opinion, leveraging the concept of Grouping JSON by values can greatly enhance efficiency. By employing the group_by method and simplifying the output, you can easily obtain the desired results.

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 hierarchical structure in the DOM that mirrors an HTML table

While working on code to navigate the DOM for a table, I encountered an unexpected surprise. The DOM (specifically in FF) did not align with my initial expectations. Upon investigation, it appears that FF has automatically inserted a tbody along with sever ...

Is there a way to assign each MySQL result to a separate variable while maintaining just one connection to the database?

I'm in the midst of a personal project and I could really use your expertise. Despite hours of research, I haven't been able to find a solid solution to my problem (likely because my PHP skills are still a work in progress). Here's the deal ...

A guide on parsing a JSON file and storing its data in MongoDB

Currently, I am in the process of parsing a JSON file which contains an array of objects. My goal is to parse this array using certain logic and proceed to save each entry into mongodb through mongoose. var fs = require('fs'); var Promise = requ ...

What is the best way to insert a new element into my heterogeneous array in Swift?

When working with a single-type array in swift, I can easily add items using various operations such as append, +=, etc. For example, this code snippet demonstrates how these operations can be used: var arr = [1, 2, 3, 4, 5] arr[0...2] = [-1, -2, -3] arr ...

What is the best way to create and send an array of dictionaries in JSON format to a server using Alamofire in Swift 3?

Trying to send an array of dictionaries in JSON format to Alamofire has been challenging for me. { "attendance": [{ "attndid":"0", "psngrtype": "student", "date":currentdate, "cuid": "25", "enttid": "21", }] } Within a tableview, I a ...

Is it possible to locate an array element within a document?

I have a list of names in an array from file.txt. My goal is to iterate through the list and verify if each name exists in myfile.txt. If a name is found, I will move on to the next one. However, if a name does not exist in myfile.txt, I want to add it to ...

Node.JS encountered an issue preventing the variable from being saved

I've been attempting to store the request.headers, but every time it outputs as [object Object] in the txt file. var http = require("http"); url = require("url"); fs = require("fs"); var events = require('events'); var even = new events.Ev ...

What is preventing the listener from activating?

I came across some HTML code that looks like this: <form id="robokassa" action="//test.robokassa.ru/Index.aspx" method="post"> <input type="text" id="OutSum" name="OutSum" value="" placeholder="Сумма пополнения"> ...

What is the purpose of setting the Z-Index on a Popper menu

If you want to see a live example demonstrating the issue, head over to codesandbox.io. My goal is to create a 'sit below' menu just like it's shown in the Material-UI documentation here. return ( <div className={classes.root}&g ...

What measures can I take to store data for a website user?

Check out my code on this website: If not, here is the HTML and JavaScript snippets: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8> <meta name="viewport" content="width=device-width, initial-scale=1.0"> ...

Retrieve a JSON file from the local file system using AngularJS

I recently started learning AngularJS and I am trying to read a JSON file from my local system. However, when I attempt to do so, I encounter an exception error that says: "Access to restricted URI denied XMLHttpRequest." Here is the code snippet: var de ...

Issues with jQuery show and hide functionality are not performing as expected

A dazzling animation has been created, fading in and out gracefully. With two buttons at hand $('.point li') to reveal distinct contents $("#"+classVal+" .table-cell") Nevertheless, upon clicking $('.point li'), I aspire for its conte ...

Display the top 10 highest numerical array elements in PHP

Every time a new 'item' is added to my website, I record the item number in a file named items_added.log. The objective now is to create a script that displays the 5 most frequently added items. Consider this array: 1 => 100 2 => 200 3 =&g ...

Using Javascript to apply unique styling to CKEditor text

Currently, I am working on a self-contained web page and utilizing CKEditor 4.6.2 for input purposes. The issue I am facing at the moment is attempting to apply a CSS class style to text that has been inserted via JavaScript. My CSS is located in the head ...

Issue with jQuery arises in chrome extensions while utilizing the popup feature

Imagine a scenario where you have a website with a disabled button. Now, you want to create a popup extension that, upon clicking a button in the popup, will remove the disabled tag from the button on the website. //manifest.json { "name": &quo ...

Execute the laravel {{action(Controller@method}} by sending a parameter from a vue.js array

Within my view created using Blade templates, I have a link with an href attribute that directly calls a Controller method. Here is an example: <a id="@{{user.id}}" href="{{action('Controller@method')}}">>update</a> Everything wo ...

Issue: ENOENT - The file or directory does not exist. uv_chdir encountered an error when attempting to create a directory and navigate into it

I am facing a challenge while developing a small application that installs files and modules in a new folder. The error I keep encountering is: { Error: ENOENT: no such file or directory, uv_chdir at process.chdir (/home/aboardwithabag/LaunchProject/n ...

Unable to retrieve object property-Attempting to access properties of undefined object

Can you help me figure out why I am unable to access the districts property in regions object? const regions = [ { region: "Hlavní město Praha", districts: "Benešov, Beroun, Kladno, Kolín, Kutná Hora, Mělník, Mladá Boleslav, Nymbur ...

What is the best way to assign unique IDs to automatically generated buttons in Angular?

Displayed below is a snippet of source code from an IONIC page dedicated to shapes and their information. Each shape on the page has two buttons associated with it: shape-properties-button and material-information-button. Is it possible to assign different ...

Tips for iterating through PHP variables to perform multiplication in a for loop

I'm currently extracting data from a form and attempting to multiply them by values on the left-hand side increased in increments of 5. I have also included an image of the outcome. Sample Code: <?php if ($_SERVER["REQUEST_METHOD"] == & ...