Improving the performance of a group by function in JavaScript

I needed a way to group an array of objects by a specific field.

Fortunately, I came across a valuable solution in the comments section of this post (by @tomitrescak:

function groupByArray(xs, key) { 
return xs.reduce(function (rv, x) { 
    let v = key instanceof Function ? key(x) : x[key]; 
    let el = rv.find((r) => r && r.key === v); 
    if (el) { 
        el.values.push(x); 
    } 
    else { 
        rv.push({ key: v, values: [x] }); 
    } 
    return rv; }, []);

}

This function works perfectly fine for me, but my array has objects with nested fields.

I want to use the function like this

console.log(groupByArray(myArray, 'fullmessage.something.somethingelse');

Thankfully, I already have a function that extracts nested fields successfully.

function fetchFromObject(obj, prop) {

if(typeof obj === 'undefined') {
    return '';
}

var _index = prop.indexOf('.')
if(_index > -1) {
    return fetchFromObject(obj[prop.substring(0, _index)], prop.substr(_index + 1));
}

return obj[prop];

}

You can use it like this

var obj = { obj2 = { var1 = 2, var2 = 2}};

console.log(fetchFromObject(obj, 'obj2.var2')); //2

Could someone assist me in integrating my function into the grouping function?

Answer ā„–1

To alter the line

let value = key instanceof Function ? key(element) : element[key];

you can update it to

let value = key instanceof Function ? key(element) : fetchValueFromObject(element, key);

to retrieve a value from any nested key.

Answer ā„–2

function groupByProperties(inputArr, properties){
 var props=properties.split(".");
 var result=[];
 main:for(var i=0;i<inputArr.length;i++){
  var value=inputArr[i];
  for(var j=0;j<props.length;j++){
    value=value[props[j]];
    if(!value) continue main;
  }
  result.push(value);
 }
return result;
}

Example Usage:

groupByProperties({a:{b:2}},{a:{b:undefined}},{a:{b:3}},"a.b")//returns [2,3]

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 JSON response is not being returned by the static React App hosted on Microsoft

Seeking assistance from anyone who may have faced and resolved a similar issue. Our React application is deployed on Azure Static Web App and operates smoothly, but we are stuck on configuring it to return JSON instead of HTML in its responses. Within our ...

I am only looking to retrieve two decimal numbers, but it appears that the toFixed() method is not functioning as expected

I am attempting to truncate my result variable to two decimal places, but nothing seems to be working. Even when using the Number() function, it appears that the price variable is treated as a string. However, I can't seem to get it to work properly a ...

more efficient method for gathering information and refreshing a database

Presented here is a method for form submission. In reality, there are many more text inputs to consider. While everything functions properly, I am seeking a more concise approach, especially on the server side. This is due to the fact that the data-col ...

What is the best way to retrieve an ID from a select multiple using Element?

I am working on a select element for assigning persons to a project. My goal is to send the ID of the selected person object to a specific function. Here is what I have tried so far: <el-form-item label="Assign to:" prop="person"> & ...

Webpack encountered an error: SyntaxError due to an unexpected token {

I recently implemented Webpack for my Django and Vue project, but I encountered an error when trying to run webpack. Can anyone help me troubleshoot this issue? $ node --use_strict ./node_modules/.bin/webpack --config webpack.config.js node_modules/webp ...

Pass a variable through AJAX during page load

I attempted to implement code for sending a variable from the view to the controller, but unfortunately my code is not functioning and I am encountering an error. An error message stating: Uncaught ReferenceError: $ is not defined is being displayed. V ...

Formatting dates with a DIV element

<div> <strong>Date: </strong> ${dateInUtc} </div> The timestamp (2021-12-09T15:43:29+01:00) in UTC format needs to be reformatted as 2021-12-09 - 15:43:29. Is there a way to achieve this without relying on ext ...

What are the effects of calling callback(false) and callback(true)?

I'm currently diving into a nodejs chat project, and Iā€™m a bit confused about the outcome when callback(false) and callback(true) are triggered in this context... io.sockets.on('connection', function(socket){ socket.on('new user& ...

The jQuery validation code is functioning properly, yet it is resulting in the same files being uploaded to both separate folders

Below is the query code I am using, and it seems to be working well: $("#formAbout").validate({ ignore:[], errorPlacement: function (error, element) { var lastError = $(element).data('lastError'), ...

Showing a randomly generated string on a TextView within a user interface

Hello everyone! I've been working on an Android project where I have a number of strings stored in my string.xml file that I want to display on a TextView based on a random number. Here is the code snippet: int randCropPercentage = (int) Math.ceil(Ma ...

Tips for appending the id of an active element to a URL

My goal was to include the id value of the active element in a URL and then redirect to that URL with a button click. HTML <div class="icon" tabindex="0" id="company"> <img src="company.png"> </div> <button type="submit" onclick= ...

My React JS page suddenly turned blank right after I implemented a setState() function within my functional component

I was working on my code and everything seemed fine until I tried to incorporate the setState function with setcategory and setvalue. However, after making this change, my react page suddenly went blank. Can anyone help me identify what went wrong and pr ...

What is the best way to transform an array of objects into an array that contains a distinct identifier in JavaScript?

I am currently working with an array of objects structured like this: { "data": [ { "id": 1, "from": "2022-08-01", "to": "2022-08-05", & ...

Looking for a way to search through an array of objects by attribute in Java?

In Java, is there a way to search an array of objects by a private attribute using the Array.binarySearch method? I am familiar with sorting techniques that involve creating a class that implements Comparator and passing it in to Array.sort. But I cannot s ...

Alter the values of the <form> element prior to submission

I am in need of submitting a form to Salesforce for creating a case. Before the submission of the form, I require changing the form values based on which button is clicked. I have designed a form with two buttons - when the first button is clicked, the cu ...

Nonspecific _POST parameter error encountered while utilizing XMLHttpRequest()

I am currently experimenting with Ajax to add data into a database using the POST method. However, I am facing an issue where PHP is unable to recognize the post variables being sent. ajax: function createUser() { var _id=document.getElementById('ne ...

Ways to customize the default countdown timer

I came across this amazing project at https://codepen.io/mattlitzinger/pen/ysowF. While the project is wonderful, I am looking to make some modifications to the code, specifically targeting a specific date. Here is the JavaScript code snippet: var tar ...

Can a way be found to block a particular metafield from being updated in WordPress?

Is there a way to prevent WordPress from storing the year, month, and day arrays? I have written JavaScript code to combine these three values into one and store it in a hidden input field. Therefore, I do not need the individual year, month, and day val ...

The transmission of values to various conditionals in JavaScript

Within my input field, I am currently verifying two conditions... If the input field contains a valid email format If the input field ends with a certain domain $('#newsletter_submit').on('click', function () { document.getEleme ...

How to trigger a function in a separate component (Comp2) from the HTML of Comp1 using Angular 2

--- Component 1--------------- <div> <li><a href="#" (click)="getFactsCount()"> Instance 2 </a></li> However, the getFactsCount() function is located in another component. I am considering utilizing @output/emitter or some o ...