Tips for manipulating deeply nested arrays of objects within an array with JavaScript

I need assistance with calculating the average of ratings within nested array objects that are inside another array. Below is the array provided:

    let arr = [
[{"category":"behavioural", "rating":3}, {"category":"technical", "rating":4.5}],
[{"category":"behavioural", "rating":1}, {"category":"technical", "rating":2.5}],
[{"category":"behavioural", "rating":4}, {"category":"technical", "rating":2}]
]

The goal is to compute the average rating for each category and then save it in an object.

Desired outcome:

"metricsaverage" : {
    "behavioral" : 2.66,
    "technical" : 3
}

In this output, 2.66 and 3 represent the average ratings of all items belonging to their respective categories from the nested array of objects.

Answer №1

Code Example:

// Sample input array
let data = [
[{"type":"fruit", "price":3}, {"type":"vegetable", "price":5}],
[{"type":"fruit", "price":2}, {"type":"vegetable", "price":4}],
[{"type":"fruit", "price":4}, {"type":"vegetable", "price":6}]
];

// Convert multi-dimensional array into single dimension
let flattenedArray = [].concat(...data);

// Grouping by type and creating an object using Array.reduce() function
const groupByType = flattenedArray.reduce((group, item) => {
  const { type } = item;
  group[type] = group[type] ?? [];
  group[type].push(item.price);
  return group;
}, {});

// Calculate the average price based on the type array
Object.keys(groupByType).forEach((item) => {
    const len = groupByType[item].length;
    groupByType[item] = groupByType[item].reduce((a, b) => a + b)/len;
})

// Output the result
console.log(groupByType);

Answer №2

Check out this live demonstration: https://jsfiddle.net/galeroy/ot1pkvqg/4/

  let data = [
      [{"category":"behavioral", "rating":3}, {"category":"technical", "rating":4.5}],
      [{"category":"behavioral", "rating":1}, {"category":"technical", "rating":2.5}],
      [{"category":"behavioral", "rating":4}, {"category":"technical", "rating":2}]
    ]

    var behavioralTotal = 0,
        behavioralItems = 0,
        technicalTotal = 0,
        technicalItems = 0;

    data.forEach(function(set){         
      set.forEach(function(item){
        if(item.category === 'behavioral'){
          behavioralTotal += item.rating;
          behavioralItems++;
        }
        else if (item.category === 'technical')
        {
          technicalTotal += item.rating;
          technicalItems++
        }
      })
    });

    console.log(
      'metricsaverage = { \n' +
        '"behavioral" : ' + (behavioralTotal/behavioralItems).toFixed(2) + ',\n' +
        '"technical" : ' + (technicalTotal/technicalItems).toFixed(2) + '\n' +
      '}'
    )

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

Having difficulty extracting image and product names from Amazon or Flipkart pages using Jsoup

I'm having trouble retrieving the main image and product name from Amazon or Flipkart using Jsoup. This is my Java/Jsoup code: // For amazon Connection connection = Jsoup.connect(url).timeout(5000).maxBodySize(1024*1024*10); Document doc = connectio ...

Implementing translation functionality within an AngularJs controller

Utilizing angular translate for translating certain words in the controller, with translation stored in json files within the html. // LABELS var monthNames = [ "January", "February", "March", "April", "May", "June", "July", "August", "Septe ...

Enable the ability for anchor links to be clickable when the CSS media print format is used to generate

To illustrate: <a href="https://www.google.com">Google anchor link</a> on the website, it displays as: Google anchor link When printed, it shows as: Google anchor link(https://www.google.com) To address this issue, I included in the CSS: ...

Using Javascript libraries on a Chromebook: A comprehensive guide to getting started

Doing some coding on my chromebook and wondering if it's possible to download and utilize libraries such as jQuery. Would really appreciate any assistance with this! ...

In React and Editor.js, the forEach method in the If/Else statement is successfully adding paragraphs but not headlines. Interestingly, this issue seems to be isolated

Looking for assistance with rebuilding my dashboard to React in order to use Editor.js for blog content instead of a textarea. Currently using Editor JS as the editor. On my local machine, everything is working perfectly. I write an article, click Create ...

What is the best way to transform my numpy array's shape from (512) to (512,) using Python 3.x?

I am a beginner in Python and I recently tried to reshape a NumPy array multiple times to match my desired shape, but I haven't been successful. Currently, my array has a shape of 512. However, I want to change it to have a shape of (512,). Can anyone ...

Is there a way to prevent users from dropping links or images into an input field

Is there a way to prevent users from dropping links or images into an input box? I'm open to using JavaScript or jQuery. Here is what I have attempted so far: http://jsfiddle.net/eRqzz/ $("input#fl_search, input#fl_search_bdy").on('drop', ...

Utilizing React Classes for File Organization in Three.js

I have successfully created a three.js application, but I am facing a challenge in organizing my functions into separate files. There is a specific mesh function that I would like to store in its own dedicated file. Here are my functions: componentDidMo ...

Having trouble with the clip-path in d3.js liquid fill gauge

Attempting to integrate the d3.js liquid fill gauge into my angular2 webapp has been a challenge. The clippath functionality seems to be malfunctioning, resulting in no wave being generated at all. https://i.stack.imgur.com/3Bmga.png instead of https://i. ...

Finding the IST date time (YYYY-MM-DD HH:mm:ss) in a Node.js environment is a common requirement. Let's

I recently used the code below to retrieve the current time and date in IST: const x = new Date().toISOString().replace(/T/, ' ').replace(/\..+/, '') Output: 2020-09-01 17:49:48 However, I actually need to obtain the time in IST ...

Having trouble with JavaScript function returning false?

I am trying to call a JavaScript function on an ASP.NET button client click event and want to prevent postback. The function is working, but it is not preventing the page from posting back. Here is my JavaScript code: function User2Check() { v ...

Exploring the functionality of the `super()` method in TypeScript

I'm trying to enhance the standard JavaScript Error class by adding another property called code, but for some reason, TypeScript is not allowing me to do so. Here is the code snippet: export class HttpError extends Error { public message: string ...

Using TypeScript to handle text resolution through the command line interface

Currently, I am developing a CLI application using TypeScript and employing enquirer for the purpose. More information about enquirer can be found here. In my project, I have a JSON object defined as follows: const person = { name: 'Mohan', ...

How to swap out identical elements in a stdClass array using PHP

How can I ensure that the $online_performers variable only returns a unique value for id 2? Do I have to first convert them into a standard array or is it possible without doing so (removing all duplicates)? Please review my new code for this. Array ...

Hold on for the asynchronous operation to complete before redirecting in KoaJS

Currently, I am facing a challenge in spawning a child process to manage some POST data in NodeJS (utilizing the Koa framework). My goal is to wait for the child process to complete before redirecting, but due to the asynchronous nature of the child proce ...

The incorrect order of CSS in NextJS production build

When working on my project, I make sure to import CSS files both from local sources and node modules: //> Global Styling // Local import "../styles/globals.scss"; // Icons import "@fortawesome/fontawesome-free/css/all.min.css"; // Bootstrap import "boot ...

I am confused as to why I am encountering an issue with req.file being "undefined" when attempting to upload a file using multer

Trying to implement a feature where users can upload files using a form, but encountering issues with multer in the controller file. When using upload.single('foobar'), the image is returning as "undefined", causing errors in the application. Spe ...

Having trouble with jest mocking a function - it's not functioning as expected

I decided to create a simple test using jest to simulate a date change function. Here is the code snippet: import React from 'react'; import '@testing-library/jest-dom'; import { render, screen } from '@testing-library/react' ...

getting data from JavaScript function by making an asynchronous request to RESTful API

My current challenge involves calling a JavaScript method that utilizes AJAX to access a REST service and then return the response to the original call. While this may seem straightforward, I have scoured Stack Overflow for answers but haven't found a ...

Angular is having trouble with binding

What seems to be the issue in this code snippet? JSFiddle. function SecondCtrl($scope, Data) { $scope.data = Data; $scope.reversedMessage = function(message) { return message.split("").reverse().join(""); }; } ...