Arranging elements in an array based on multiple properties using underscores

At work, I was tasked with organizing elements in an array based on their similar properties.

The issue at hand is outlined as follows:

var order = [
    {
        "tot":1,
        "ru":"R401",
        "area":"RFCC",
        "unit":"OFFSITE",
        "equipment":"37 P 552 A",
        "parameter":"Speed"
    }, {
        "tot":1,
        "ru":"R401",
        "area":"RFCC",
        "unit":"OFFSITE",
        "equipment":"37 P 552 A",
        "parameter":"Discharge pressure"
    }, {
        "tot":1,
        "ru":"R401",
        "area":"RFCC",
        "unit":"OFFSITE",
        "equipment":"37 P 552 A",
        "parameter":"Speed"
    }, {
        "tot":1,
        "ru":"R401",
        "area":"RFCC",
        "unit":"RCU",
        "equipment":"37 P 552 B",
        "parameter":"Discharge pressure"
    }
]

If I group these elements by 'ru', 'area', 'unit', 'tot', 'equipment' and 'parameter', the result would be:

var result = [
    {
        "ru":"R401",
        "area":"RFCC",
        "unit":"OFFSITE",
        "tot":2,
        "equipment":"37 P 552 A",
        "parameter":"Speed"
    }, {
        "ru":"R401",
        "area":"RFCC",
        "unit":"OFFSITE",
        "tot":1,
        "equipment":"37 P 552 A",
        "parameter":"Discharge Pressure"
    }, {
        "ru":"R401",
        "area":"RFCC",
        "unit":"RCU",
        "tot":1,
        "equipment":"37 P 552 B",
        "parameter":"Discharge Pressure"
    }];

After some trial and error, I arrived at the following code snippet:

  var groups = _.groupBy(order, function(value) {
    return value.ru + "#" + value.area + "#" + value.unit + "#" + value.equipment + "#" + value.parameter + "#";
  });

  groups = _.map(groups, function(group) {
    return _.extend(group[0], {tot: group.length});
  });

I am now facing a challenge in grouping similar results. If anyone has any ideas or suggestions, please feel free to assist me. Thank you in advance.

Answer №1

What do you think of this:

var data = [
    {
        "total":1,
        "resource":"R401",
        "area":"RFCC",
        "unit":"OFFSITE",
        "equipment":"37 P 552 A",
        "parameter":"Speed"
    }, {
        "total":1,
        "resource":"R401",
        "area":"RFCC",
        "unit":"OFFSITE",
        "equipment":"37 P 552 A",
        "parameter":"Discharge pressure"
    }, {
        "total":1,
        "resource":"R401",
        "area":"RFCC",
        "unit":"OFFSITE",
        "equipment":"37 P 552 A",
        "parameter":"Speed"
    }, {
        "total":1,
        "resource":"R401",
        "area":"RFCC",
        "unit":"RCU",
        "equipment":"37 P 552 B",
        "parameter":"Discharge pressure"
    }
];
var processedData = [];
data.forEach(item=>{
    let index = -1;
    processedData.forEach((element,i)=>{
        if (element.resource==item.resource && element.area==item.area && element.unit==item.unit && element.total==item.total && element.equipment==item.equipment && element.parameter==item.parameter){
            index = i;
        }
    });
    // console.log(index);
    if(index==-1){
        processedData.push(item);
    }else{
        processedData[index]["total"] = processedData[index]["total"]+item["total"];
    }
});
console.log(processedData);

Answer №2

One way to optimize your code is by directly updating the tot property of the merged object in your "index" map/object without grouping them:

Check out this solution using the reduce method:

const order = [
    {
        "tot":1,
        "ru":"R401",
        "area":"RFCC",
        "unit":"OFFSITE",
        "equipment":"37 P 552 A",
        "parameter":"Speed"
    }, {
        "tot":1,
        "ru":"R401",
        "area":"RFCC",
        "unit":"OFFSITE",
        "equipment":"37 P 552 A",
        "parameter":"Discharge pressure"
    }, {
        "tot":1,
        "ru":"R401",
        "area":"RFCC",
        "unit":"OFFSITE",
        "equipment":"37 P 552 A",
        "parameter":"Speed"
    }, {
        "tot":1,
        "ru":"R401",
        "area":"RFCC",
        "unit":"RCU",
        "equipment":"37 P 552 B",
        "parameter":"Discharge pressure"
    }
]

const merged = Object.values(order.reduce((acc, curr) => {
  const key = `${curr.ru}#${curr.area}#${curr.unit}#${curr.equipment}#${curr.parameter}`;
  if (key in acc) acc[key].tot += 1;
  else acc[key] = Object.assign({}, curr);
  return acc;
}, {}));

console.log(merged);
console.log(merged.map(d => d.ru));

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

Bidirectional data binding in AngularJS for <option> elements generated from an AJAX request

I have built a Controller called WebsiteController with the following functionality: JApp.controller('WebsiteController', function($scope, $resource) { var UsersService = $resource('/auth/users', {}); $scope.adding = false; ...

A common challenge in React is aligning the button and input line on the same level

I'm currently working on a React page where I have an input field and a button. My goal is to align the bottom edge of the button with the bottom line of the input. Here's the code snippet I have: `<form className='button-container'& ...

Navigating ng-view using $location.path()

Incorporating an answer from another StackOverflow post, I'm attempting to utilize a link in the header to redirect ng-view on Index.html. When navigating directly to pages using: http://server/#/page, the application functions smoothly (no console e ...

Exploring a multitude of data within a hefty json log document using node.js

I am dealing with a JSON file named sensorlogs.json that contains data from different sensors transmitting at varying frequencies. The timestamps in the file are not in order and one sensor may have missing entries. The goal is to analyze each sensor&apos ...

Check if the Datatable is empty using an alert

Working with Datatable V. 1.10.12, the data is successfully rendered using PHP/Ajax/JSON. Recently, I added some buttons, including a delete button outside the table to remove selected rows. Everything works fine, except for when the table is empty and the ...

The clarity and completeness of images on canvas are lacking

I've experimented with numerous examples found on the internet, but none of them seem to be effective. My goal is to display a full image on a canvas without it being zoomed in and losing quality. In addition, I attempted to rotate images (from stand ...

Obtain the search query stored in the state using ReactJS

I'm currently exploring ReactJS and attempting to retrieve the value entered in a search input box, then store it in a state. Here is my code snippet: <form className="search-form" onSubmit={this.handleSubmit}> <input type="search" na ...

Navigating a collection of characters in the C++ programming language

When I receive a string of characters from the command line like this: progname 0102030405060708 The variable argv[1] is declared as char *argv[] So, the value of argv[1] is 0102030405060708 This string is meant to be interpreted as a list of 8 chara ...

Using Javascript to extract the date from a specific field and then computing the date of birth

I am currently working on a form which includes a datepicker for the field of birthdate. Additionally, I have an age input field that I want to automatically fill with the person's age based on their birthdate (comparing it to the current date). My m ...

What is the best way to determine the index of an element within an array when using the C

#define ID_A 5 #define ID_B 7 #define ID_C 9 const int id_arr={ ID_A, ID_B, ID_C, }; If I want to find out the offset of ID_C in id_arr without running the code, is there a way to achieve this using macros or any other method? ...

Vue 3 project experiencing issue with Bootstrap 5 tabs failing to update upon tab click

Currently, I'm in the process of developing a vue3 application with bootstrap 5. As part of this project, I am implementing tabs. Although I can successfully click on the tabs, I have encountered an issue where the tab-content remains fixed on the ini ...

Send the window to Google before submitting a search using Google

I've successfully sent a query to Google using window.location.href, but I'm stuck on how to submit the search form to view the results. I have my javascript code that directs the window to Google with the query from the search-box, but I'm ...

What is the reason behind encountering a segfault on Linux when declaring a 2D array of adequate size, while not experiencing the same issue

Issue I've encountered a problem while trying to declare a large 2D Array (also known as matrix) in C / C++. The issue is that it crashes with a segmentation fault only on Linux. Interestingly, the Linux system has significantly more RAM installed co ...

Are non-local variables in Node.js considered safe to use?

Would it be secure to implement this code in Node.js/Express.js? // using Object.create(null) to avoid key collisions // refer http://www.devthought.com/2012/01/18/an-object-is-not-a-hash/ var theHash = Object.create(null); exports.store = function (req, ...

Incorporating an HTML page into a tab through Ajax with the help of a for loop, utilizing Bootstrap 3

Currently, I am developing an Address Book application where the main page displays a series of tabs with the names of the contacts from the contact.objects using a for loop in the code below. How can I utilize ajax to load the information of each contact ...

What is the best way to set Google Sheets to automatically refresh every minute?

I am using an ImportJSON script in my Google Sheets that I got from this source. Currently, my code looks like this: =ImportJSON("http://date.jsontest.com/","/time", "") This code retrieves the current time, but my problem is that it does not automatical ...

What is the most frequently occurring byte array within a byte array in C#?

Is there a way to extract the most frequently occurring byte array from another bytearray? For example: Given input byte array: 41, 4, 5, 42, 4, 5, 42, 4, 5, 42, 2 The desired output: 4, 5, 42 Any suggestions or solutions would be greatly appreciated. ...

Button Triggering Javascript

Looking for a handy solution that allows users to either accept or reject a website's cookie policy. I came across an interesting library called cookies-EU-Banner (found at ) which seems to be quite popular. It recognizes when the user clicks on Reje ...

ng-switch not refreshing on its own

I've encountered a strange issue with ng-switch that I can't seem to solve. On the top of my page, I have: #content{"ng-switch" => "root.showAlert"} %div.alert.ng-cloak#alert{"ng-switch-when" => "true"} {{root.alert.message}} %di ...

Tips for preventing NextJS from including a dynamically imported component in the main _app.js bundle while utilizing Module Aliases

Currently, I am in the process of transforming some shared-ui components into dynamically imported ones within NextJS 11. I have set up module aliases using @nx/next:library, for example @my-site/shared-ui, all exported from an index.ts file as shown belo ...