Can you determine the top-rated product category by comparing the arrays provided in JavaScript?

Here are two arrays to consider:

const items = [
  {
    name: 'item1',
    type: 'Fruit'
  },
  {
    name: 'item2',
    type: 'Vegetable'
  },
  {
    name: 'item3',
    type: 'Snack'
  }];


const prices = [
  {
    name: 'item1',
    price: 5,
  },
  {
    name: 'item2',
    price: 8
  },
  {
    name: 'item3',
    price: 10,
  }];

If we want to determine the category with the highest total price, how can this be achieved? For instance, item1 and item2 fall under the same category 'Produce' so the total for Produce would be 5 + 8 = 13.

One approach could involve creating a modified array of items where each element includes the corresponding price from the second array. From there, iterating through the adjusted array to generate a final array consisting of objects containing category and totalPrice might be considered.

In this process, if the final array already contains a category object, updating the total by adding the new price value is necessary; otherwise, inserting a new entry with category: totalPrice will suffice.

Is it possible to optimize this procedure further?

Answer №1

It is common knowledge that canonical grouping follows this pattern...

const prodsByCategory = products.reduce((acc, p) => {
  let cat = p.category;
  if (!acc[cat]) acc[cat] = [];
  acc[cat].push(p);
  return acc;
}, {});

To enhance optimization, we can make some modifications to the existing code.

const prodsByCategory = products.reduce((acc, p) => {
  let cat = p.category;
  // maintaining an array and total instead of just an array
  if (!acc[cat]) acc[cat] = { products: [], totalRate: 0 };
  // push product and add rate to the total
  acc[cat].products.push(p);
  acc[cat].totalRate += rateForProduct(p) || 0;
  return acc;
}, {});

We will also need a function called rateForProduct for the rate lookup:

const rateForProduct = product => {
  return rate.find(r => r.name === product.name)?.rate || 0;
}

The result should be an object categorized by category with each value containing a totalRate property. Sort these entries to maximize the first one. Here's an example...

const products = [{
    name: 'prod1',
    category: 'Meat'
  },
  {
    name: 'prod2',
    category: 'Meat'
  },
  {
    name: 'prod3',
    category: 'Dairy'
  }
];

const rate = [{
    name: 'prod1',
    rate: 23,
  },
  {
    name: 'prod2',
    rate: 36
  },
  {
    name: 'prod3',
    rate: 50,
  }
];

const rateForProduct = product => {
  return rate.find(r => r.name === product.name)?.rate || 0;
}

const prodsByCategory = products.reduce((acc, p) => {
  let cat = p.category;
  if (!acc[cat]) acc[cat] = {
    products: [],
    totalRate: 0
  };
  acc[cat].products.push(p);
  acc[cat].totalRate += rateForProduct(p);
  return acc;
});

const sortedEntries = Object.entries(prodsByCategory).sort((a, b) => b[1].totalRate - a[1].totalRate);

const bestEntry = {
  category: sortedEntries[0][0],
  rate: sortedEntries[0][1].totalRate
}
console.log(bestEntry);

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

How to Call a Nested Object in JavaScript Dynamically?

var myObj = { bar_foo : "test", bar : { foo : "hi there"; }, foo : { bar : { foo: "and here we go!" } } } How can we achieve the following: var arr = [["bar", "foo"], ...

Ensuring Form Completion by Validating Input Fields

I've recently developed a Contact form using PHP, but I encountered an issue with the submit button. It currently sends information through an Ajax script to prevent the form from closing after the user hits send, even if all fields are completed. Ho ...

The logout confirmation message functionality in Laravel 8 is malfunctioning

In my Laravel project, I am attempting to implement a logout confirmation message that will pop up when a user clicks on the logout button. Here is the code I have added to my navbar.blade.php: <a class="dropdown-item" id="logout" hr ...

Leveraging jQuery's load within a series of sequential operations

I am currently working on populating different cells in a table with the IDs #RECALRow1, #RECALCol1, and #RECALBodySum. Each cell is being filled from a database using AJAX with jQuery's load method. In my initial approach, I had separate functions f ...

Python code to transform an integer array into a binary array

I'm attempting to convert an array of integers into binary format using Python 2.7. Here's a simplified version of the code I'm working with: #!/usr/bin/python import numpy as np a = np.array([6, 1, 5, 0, 2]) b = np.zeros((5)) for i i ...

How do you trigger the playback of a specific audio file when a user clicks on it?

I'm currently working on an interactive music app that mimics the functionality of a piano. Users are able to click on different boxes on the screen, triggering a unique musical note to play. While I initially considered manually collecting all the I ...

Analyzing Compatibility and Ensuring Security

I recently started using Parse and have been exploring the documentation and answered questions. However, I still have a couple of inquiries on my mind. Firstly, I discovered that the Javascript SDK does not function on IE9 and IE8 without an SSL certific ...

Showing a 2D array in Jquery within an MVC environment - what's the solution?

I am in the process of building an MVC application. My goal is to transmit data from the controller and display it using JQuery. I have constructed an array in the controller and sent it to JQuery using Json. Here is the array... And here is the JQuery ...

Alternative Sorting Techniques for Arrays

Issue: A set X of length M is considered pseudo-arranged if it can be transformed into a non-decreasing sequence by swapping elements at most once. Select an index i where 1≤i≤M−1 and exchange Xi with Xi+1 Given a set X, determine its pseudo-sortin ...

Encountered a connection error in the Spring Boot application: net::ERR_CONNECTION_REF

Currently working on a school project developing a Spring Boot application using Restful. The application runs smoothly locally, but when deployed to AWS, I am encountering an "net::ERR_CONNECTION_REFUSED" error for all my GET and POST requests sent to the ...

Can Vue.js be configured to reload specific components only?

Can a specific component be reloaded in a Vue component that contains multiple components? For example, if there is a component structured like this: Main component <template> <button>Button<button> <component1></component> ...

There seems to be an issue with the Node JavaScript file not updating automatically

Currently facing an issue while trying to develop my first node application. The problem lies with the JavaScript file, as my CSS file is working fine which is causing confusion for me. Here is a snippet of my app.js code: var express = require("express") ...

Limit the input to a specific format

Currently developing a JavaScript application, but having some confusion with Regular Expressions. The main goal is to allow users to input a specific format of strings in a text area for the application to process accordingly, thus requiring restriction o ...

Highlight a section of the innerHTML code

Currently, I am working on creating a table that will showcase the dates of the upcoming 10 days. In order to populate the table with the day, date, month, and year, I have implemented the following JavaScript code: document.getElementById(i).innerHTML = ...

How can I asynchronously parse JSON data from a URL on a Windows phone and display it in a

As an Android developer exploring the world of Windows Phone for the first time, I came across this resource on how to handle list boxes in Windows Phone 7/8. However, my challenge now is parsing JSON from a URL instead of XML as shown in the example. Whil ...

Image swaps with timer for button

I am working on a project where I have a page with 5 image buttons arranged horizontally. The objective is to have the images on each button change sequentially every 3 seconds in a continuous loop. Here is my code: $(document).ready(function (){ Beg ...

Accessing data in vuex can result in Firebase SnapShot.val() returning null

I am developing an application that allows access for students, staff, and non-teaching staff. Here is how my form data is structured: formData: { name: "", email: "", password: "", select: null }, options: ["Student", "St ...

Making AngularJS 'PUT' requests: The process of submitting only the data in a form

I am facing an issue while updating user data in Angular. When I send a 'PUT' request, the entire user $scope is being sent instead of only the fields visible on the form. To retrieve and update the data, I am using a Factory. Below is my edit f ...

Updating the DOM using jQuery after receiving an AJAX response

I'm grappling with the most effective way to modify the DOM after receiving an AJAX response. I prefer to showcase the code rather than attempt to articulate my dilemma. // page contains several checkboxes $("input[type='checkbox']").live(& ...

What causes the slow loading of a div from an external URL?

I have created two buttons that open different PHP pages. When I click on one button, it loads the respective URL into a div. However, when switching to the other button, there is a noticeable delay in loading the new page. The transition between buttons ...