Grouping objects in Linq JS based on the first letter of their names

list = [
    {
        "Id": "547370FD-5185-47F7-B980-C439A010E028",

        "FirstName": "Rahul",
        "LastName": "Grag"
    },
    {

        "Id": "547370FD-5185-47F7-B980-C439A010E027",
        "FirstName": "Mohit",
        "LastName": "V"
    },
    {

        "Id": "547370FD-5185-47F7-B980-C439A010E026",
        "FirstName": "Sanjeev",
        "LastName": "Kumar"
    },
    {

        "Id": "547370FD-5185-47F7-B980-C439A010E025",
        "FirstName": "Manish",
        "LastName": "Kumar"
    },
    {

        "Id": "547370FD-5185-47F7-B980-C439A010E024",
        "FirstName": "Rahul",
        "LastName": "Jain"
    },
    {

        "Id": "547370FD-5185-47F7-B980-C439A010E023",
        "FirstName": "Shikha",
        "LastName": "K"
    }
];

To organize these objects based on the first letter of their FirstName, you can create a function that groups them accordingly.

Answer №1

This code snippet is used to group objects based on the first letter of their names. It creates an object where each key corresponds to a unique first letter, and the value is an array containing all objects with the same first letter in their FirstName property.

var nameGroups = {};

list.forEach(function(object) {
  if (!object.FirstName || !object.FirstName.length) return;

  var firstLetter = object.FirstName[0];

  if (!nameGroups[firstLetter]) {
    nameGroups[firstLetter] = [];
  }
  nameGroups[firstLetter].push(object);
});

To ensure consistency in capitalization, you can use firstLetter.toUpperCase() if needed.

Answer №2

If you happen to be utilizing linq.js, this task is quite simple.

With the assistance of linq.js, one can easily accomplish this by executing: var query = Enumerable.From(list).GroupBy("$.FirstName[0]");

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

Triggering a Dialogflow Chat Window with a click on a Material-UI Floating Action Button in a ReactJS application

I have encountered an issue in my code where I am attempting to toggle the display of a Dialogflow Chat Window, <ChatWidget />, when a user clicks on the Material-UI Floating Action Button, <FloatingActionButton/>. The default state is set to f ...

Is there a way to remove an element from one table and add it to another table upon clicking the submit button using JavaScript?

Seeking assistance as a newcomer in the world of JavaScript. A wise quote goes here An array filled with fruits such as mango, apple, orange, and kiwi is declared as "fruits". Another thought-provoking quote follows... The task at hand involves man ...

What causes AngularJS to alter my GET parameters when using $http?

I am currently making a basic GET request to a REST service in order to obtain a list of users and sort them by their usernames. Using jQuery, the process runs smoothly: $.getJSON('/api/users', { sort: { username: 'asc' } }, funct ...

Python script malfunctioning due to non-ASCII character 'xc5' causing disruption

After running my node.js server, an array is generated containing various names such as ["Daniel Guillen","Sarah Tremaine Milam","Karen Ann"...."Chris Doyle","Katie Gould"]. While attempting to convert this array to a CSV file using a Python script, I en ...

Creating an email validation regex that works in both Ruby and Javascript

Utilizing a regular expression in my model and relying on the Judge gem for client side validation has proven to be beneficial. The Judge gem leverages the models for its client side validation, using the user email regex in both Ruby and javascript. The ...

Tips for substituting a pair of terms with equivalent ones from an array using Arabic JavaScript

In my array, I have the months written in English and the days of the week also in English. I am trying to replace the English words with their Arabic equivalents at the corresponding index in the array. My code looks simple and clean, but for some reason ...

Ensure that the header smoothly navigates to a specific section within a separate component

Should I have this app that in the end has just 1 page? My current file structure is divided per section. I want to create a header that when clicked scrolls to a certain section (which is located in another component, not in the same file as these compone ...

Updating textbox values with ajax results in the page refreshing and the newly assigned values being lost

I'm currently working on updating a section of my webpage using AJAX instead of C#, as I don't want the page to refresh. All I need to do is execute a SELECT query to retrieve the current client from the SQL database and populate the correspondin ...

Iterating through data using the $.each method within an AJAX request sent to

Currently diving into the realm of ajax and php, I am facing an issue. I have set up an ajax request, communicating with a php controller to retrieve data in json format. The necessary information has been successfully received as confirmed by my tests. ...

What is the best way to classify Arrays and Objects together?

I am facing a situation where I have an array containing 3 Objects, but the second Object does not include an array inside the 'Data' Object. My main challenge is to loop through each 'Artist' in the correct order using ng-repeat, but ...

Is there a way to round a number in JavaScript with negative precision similar to the rounding function in Excel?

Is there a way to round the value 8904000 to 8900000 using Math.round? An example of this in MS Excel is shown below: =round(8904000,-5); ANS: 8900000 I attempted to use Math.round with a second argument, but it did not work as expected: Math.round(8904 ...

Alter the color of the dropdown background when it is changed

Currently, I am utilizing the Semantic UI React CSS library and find myself in need of changing the background color of dropdowns once an option is selected. https://i.sstatic.net/yZBK7.png to https://i.sstatic.net/LxTtT.png <Dropdown placeholder=&apo ...

Ways to include additional parameters in jQuery ajax success and error callbacks

When working with a jQuery AJAX success/error function similar to the following: success: function (data, textStatus, jqXHR) { } error: function (jqxr, errorCode, errorThrown) { } I am wondering if there is a method where I can pass an array of valu ...

Programmatically Expand and Collapse All nodes in MUI DataGrid using ReactJS

Is there a way to programmatically expand or collapse all rows in MUI ReactJS DataGrid? What have I tried? I attempted to use the defaultGroupingExpansionDepth property as suggested in the MUI documentation: export const EXPAND_ALL = -1; export const COLL ...

What steps can I take to enable search functionality in Ckeditor's richcombo similar to the regular search feature in

I am currently developing a custom dropdown menu using the rich combo feature in CKEDITOR. One of my goals is to include a search functionality within the dropdown, such as a key press search or an input textbox search. This is how my dropdown box appear ...

Is an Ajax Call patiently anticipating the result of a separate Ajax Call?

I am facing a situation where I have two separate ajax calls that cannot be combined into one call. The first ajax call can start, and then the second ajax call can start either immediately or upon the user pressing a send button. However, the second ajax ...

Ways to enhance FormControl capabilities using prototypes

I am looking to add an observable or event emitter field (such as onMarkAsDirty) to all objects of the FormControl type. This field should be triggered when the markAsDirty method is called. I attempted to achieve this by extending the prototype of FormC ...

Under what circumstances would you need to manually specify the displayName of a React component?

After coming across an article (linked here: https://medium.com/@stevemao/do-not-use-anonymous-functions-to-construct-react-functional-components-c5408ec8f4c7) discussing the drawbacks of creating React components with arrow functions, particularly regardi ...

Handlers for event(s) not triggering on video element

In my NextJS application, I have implemented a feature to display a video file using the video element. I have added multiple event handlers to the video element: <video className='video-player' controls={true} preload='metadata&apo ...

The method of pausing a function until the result of another function is returned

There is a function named 'updateProfile()' that includes a condition, which checks for the value of variable 'emailChangeConfirm' obtained from another function called 'updateEmailAllProcessing()'. The issue lies in the fact ...