Utilizing object categories to split arrays and extract values in JavaScript with Highcharts

After receiving an array with a number of objects, my goal is to split it based on categories. Once the sum value of categories in the array reaches 15, I need to further divide the array as shown below for better organization.

Any assistance would be greatly appreciated

Array

 [Object { name="A",  categories=[2]}, Object { name="B",  categories=[3]}, Object { name="C",  categories=[1]}, Object { name="D",  categories=[1]}, Object { name="E",  categories=[1]}, Object { name="F",  categories=[3]}, Object { name="G",  categories=[1]}, Object { name="H",  categories=[1]}, Object { name="I",  categories=[1]}, Object { name="J",  categories=[3]}, Object { name="K",  categories=[2]}, Object { name="L",  categories=[2]}, Object { name="M",  categories=[2]}]

Additional Details

[{"name":"A","categories":["543","301"]},{"name":"B","categories":["100","120","390"]},{"name":"C","categories":["453"]},{"name":"D","categories":["112"]},{"name":"E","categories":["542"]},{"name":"F","categories":["534","545","547"]},{"name":"G","categories":[" 535"]},{"name":"H","categories":["390"]},{"name":"I","categories":["528"]},{"name":"J","categories":["101","492"," 320"]},{"name":"K","categories":["201","210"]},{"name":"L","categories":["102","573"]},{"name":"M","categories":["211","220"]}]

Desired Result

[[{"name":"A","categories":["543","301"]},{"name":"B","categories":["100","120","390"]},{"name":"C","categories":["453"]},{"name":"D","categories":["112"]},{"name":"E","categories":["542"]},{"name":"F","categories":["534","545","547"]},{"name":"G","categories":[" 535"]},{"name":"H","categories":["390"]},{"name":"I","categories":["528"]},{"name":"J","categories":["101"]}],[{"name":"J","categories":["492"," 320"]},{"name":"K","categories":["201","210"]},{"name":"L","categories":["102","573"]},{"name":"M","categories":["211","220"]}]]

This segment of the result will offer more guidance on achieving the desired outcome

{"name":"J","categories":["101"]}],[{"name":"J","categories":["492"," 320"]}

Answer №1

A new and creative method involving the use of Array.prototype.reduce() along with a temporary object.

let items = [{ "name": "X", "categories": ["543", "301"] }, { "name": "Y", "categories": ["100", "120", "390"] }, { "name": "Z", "categories": ["453"] }];
// More data omitted for brevity

let result = items.reduce(function (accumulator, currentValue) {
        // Logic here
    }, { array: [], count: 0, refA: undefined, refB: undefined }).array;

document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');

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

Identifying edited files within the node_modules directory: A comprehensive guide

While working with the serverless framework, I installed it using npm. During my debugging process, I made some modifications by adding console.log statements to different files within the node_modules folder. Unfortunately, I can't recall which speci ...

How to prioritize indices when querying multiple indexes in Elasticsearch?

Utilizing the Elasticsearch multi index API, I am able to query across multiple indices. However, it is important for me to prioritize my queries. As an illustration, when querying in the indices index1 and index2, the syntax would look like: /index1,ind ...

Having trouble with the GitHub publish action as it is unable to locate the package.json file in the root directory, even though it exists. Struggling to publish my node package using this

I've been struggling to set up a publish.yml file for my project. I want it so that when I push to the main branch, the package is published on both npm and GitHub packages. However, I am facing difficulties in achieving this. Here is the content of ...

Using Swig's conditional extend tag with Express.js and Node.js to leverage dynamic content rendering

Is there a way to make the extend tag for the Swig templating engine conditional or able to use a passed variable? Instead of using this code: {% extends '../layouts/layout.view' %} I would prefer to do something like this: {% extends layout ...

Guide to accessing object items in v-for in VueJs

Upon inspection, the following results are being displayed: https://i.sstatic.net/oF4Qe.png https://i.sstatic.net/21aHB.png In the Vue template code provided: <select class="form-select" v-model="post_format.wpml_language"> <option v-for="(l ...

The camera's rotation remains unchanged even after applying the transformation matrix

Is there a way to effectively apply a transformation matrix to a PerspectiveCamera? I have the transformation matrix and I am applying it to the Perspective camera using camera.applyMatrix(transformationMatrix); The camera.position is updated correctly, ...

The value from the angular UI bootstrap datepicker is unavailable when using a JQuery expression

I have a question regarding the datepicker feature from the Angular UI bootstrap library. The documentation can be found here. After selecting a date using the datepicker, I am facing an issue with retrieving the text input using jQuery expressions. When ...

Problem with div selection and dynamic content in Rails 5

Currently, I am working on developing an application using Rails 5 and Ruby 2.4.0 with Bootstrap 4 Alpha 6 integration. The issue I am facing involves a dynamic select box that loads information about the selected item into a div below it. However, each t ...

The presence of a WebXR overlay disrupts the functionality of the ThreeJS AR Controller

Currently, I am working on a school project which involves creating a webshop where users can view products in Augmented Reality (AR). I have used WebXR to add an overlay to the AR session that includes a button for repositioning the model. However, I noti ...

Determine the sequence of a div based on its class

Here is the code snippet I am working with: <div class="test"></div> <div class="test"></div> <div class="test"></div> <input type="button" class="button" value="get number"> <div class="test"></div> & ...

Is it possible to modify the font size of all text that shares a particular font size?

Lately, I've been pondering on a question. A few years ago, I created a website using regular CSS and now I want to make some changes to the font sizes. While I know that CSS variables are the recommended solution for this situation, I'm curious ...

Exploring the capabilities of window opener in AngularJS applications

I am facing an issue with a function that utilizes an API to redirect me to a callback URL. After this redirection, I need to execute a function in my core JavaScript. If I keep the function separate from AngularJS and use window.opener, it works fine. How ...

Response Headers in Google Cloud Functions

When executing a GCF triggered by an Http Request, I encounter the issue of receiving unnecessary headers along with my custom message. Here is a list of headers that are included: HTTP/1.1 200 OK Server: nginx Content-Type: application/json; charset=utf- ...

Tips for sending transactions across multiple collections in Mongoose

Important Note: I establish a connection to the database using the following code: const mongoose = require('mongoose'); const connectDB = (url) => { return mongoose.connect(url); } Issue Summary: I am faced with a situation where two diff ...

Create an interactive JSON tree structure

I am looking to create a JSON tree from an array. My array is structured like this: var arraySource = []; arraySource.push({key : "fr", value: "france"}); arraySource.push({key : "es", value: "spain"}); //... console.debug(arraySource); The desired JSON ...

Issues with object changes not reflecting in Vue.js 2.0 component rendering

I am facing an issue where my object is not updating immediately after a click event. It appears that a manual refresh or clicking on another element is necessary for the changes to take effect. How can I ensure that the object updates without the need for ...

Repetitive calling of a Node.js function

Currently, I am developing using the nodejs express framework. On my webpage, there are two buttons: 1) Submit, which triggers the following function: router.get('/record_enrich_quick/:quick', function(req, res) { console.trace(); var j ...

What is the best way to retrieve a file's creation date using the file System module in Node.js

I'm having trouble fetching the filename and file creation date to send to a client. I tried using fs.stat which provides birthtime but does not include the filename. So, my question is: is birthtime equivalent to the file created date? How can I sen ...

What is the best way to implement a custom layout with nuxt-property-decorator?

Summary of Different Header Components in Nuxt In order to set a different header component for a specific page in Nuxt, you can create separate layout files. layout ├ default.vue // <- common header └ custom.vue // <- special header for s ...

creating folding effect using javascript and css with divs

I've been searching high and low on the internet for a solution like this, but so far I haven't had any luck. It seems like there might be a JavaScript script out there that dynamically changes the css -webkit-transform: rotateY(deg) property. ...