The output from the lodash sortBy function is not aligning with the anticipated result

Sorting this array based on the attributes age and user has become my current challenge. The priority is to first sort by age, followed by sorting by user. In cases where the ages are the same, the sorting should be done based on the user attribute.

var users = [
    { 'user': 'kurt', 'age': 1 },
    { 'user': 'barney', 'age': 11 },
    { 'user': 'fred', 'sge': 3 },
    { 'user': 'alex', 'age': 7 },
    { 'user': 'box', 'age': 7 },
    { 'user': 'foo', 'age': 7 }
];

_.sortBy(users, (o) => [o.age, o.user]);

Output:

[
    { 'user': 'kurt', 'age': 1 },
    { 'user': 'barney', 'age': 11 },
    { 'user': 'fred', 'age': 3 },
    { 'user': 'alex', 'age': 7 },
    { 'user': 'box', 'age': 7 },
    { 'user': 'foo', 'age': 7 }
]

In the resulting output, it's noticed that age: 11 is positioned after age: 1, whereas it should actually come at the end. Is there a mistake in the approach I am taking here, or could this be an issue with the lodash sortBy function? The expected output should be as shown below:

Expected output:

[
    { 'user': 'kurt', 'age': 1 },
    { 'user': 'fred', 'age': 3 },
    { 'user': 'alex', 'age': 7 },
    { 'user': 'box', 'age': 7 },
    { 'user': 'foo', 'age': 7 },
    { 'user': 'barney', 'age': 11 }
]

Answer №1

Instead of specifying a second key, you can simply use the age property: _.sortBy(users, 'age');

If you want to sort based on both properties, you should do the following:

_.sortBy(users,['age','user']);

To better understand how the sorting works with the user property, try shuffling the example data a bit:

var users = [
      { 'user': 'foo', 'age': 7 }
      { 'user': 'kurt',   'age': 1 },
      { 'user': 'barney', 'age': 11 },
      { 'user': 'box', 'age': 7 }, 
      { 'user': 'fred',   'age': 3 },
      { 'user': 'alex', 'age': 7 },
    ];

    _.sortBy(users, 'age','user');

Answer №2

Here is a suggested solution:

let orderedUsers = _.sortBy(users, (item) => item.age, (item) => item.user);
// Alternatively
let orderedUsers = _.sortBy(users, [(item) => item.age, (item) => item.user]);

Answer №3

One way to implement this is:

_.orderBy(users, ["age", "user"])

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

Encountering an Uncaught Error: MyModule type lacks the 'ɵmod' property

I am currently working on developing a custom module to store all my UI components. It is essential that this module is compatible with Angular 10 and above. Here is the package.json file for my library: { "name": "myLibModule", &qu ...

JavaScript table supported by a REST API

Issue at hand: I am in search of a table component that seamlessly integrates with my web application. The challenge lies in connecting the existing REST endpoints to the table for data retrieval, whether it be paginated or not. Adjusting the endpoints t ...

Separate arrays containing latitude and longitude coordinates to map out all potential points of (latitude, longitude)

I need to identify all potential points created by latitude and longitude coordinates stored in separate arrays: a = np.array([71,75]) b = np.array([43,42]) Is there a simple method to achieve this without generating redundant pairs? I've experimen ...

Ending the Overlay

I am using an overlay: <div id="overlayer" class="overlayer"> <div id="board" class="board"></div> </div> Here are the CSS properties I have applied to it: #overlayer { position:fixed; display:none; top:0; left:0; width:100%; hei ...

With Crypto-JS, a fresh hash is always generated

I'm looking to integrate crypto-js into my Angular 8 application. Here is a snippet of my code: import {Injectable} from '@angular/core'; import * as CryptoJS from 'crypto-js'; @Injectable() export class HprotoService { public ...

Can you explain the distinction between the terms "vite" and "vite preview"?

I recently created a project template with the help of vite. While looking through my package.json file, I noticed the following section; "scripts": { "dev": "vite", "build": "vue-tsc --noEmit &&a ...

Disabling the submit button after submitting the form results in the page failing to load

I am encountering an issue with my HTML form that submits to another page via POST. After the form validates, I attempt to disable or hide the submit button to prevent double submission and inform the user that the next page may take some time to load. He ...

How to transform multi-dimensional arrays to JSON format using JavaScript (and maybe jQuery)

Currently facing a Javascript dilemma where data storage is essential in the following format: MainArray(Array(JavaScript Object, JavaScript Object, etc etc..), Array(JavaScript Object, JavaScript Object, etc etc..), etc etc..) The main array consists of ...

What is the best way to configure Jenkins to exclude or include specific component.spec.ts files from being executed during the build

Currently, I am facing an issue while attempting to include my spec.ts files in sonarqube for code coverage analysis. However, my Jenkins build is failing due to specific spec.ts files. Is there a way to exclude these particular spec.ts files and include ...

Tips for avoiding problems with quoting and using apostrophes in a JavaScript function inside a tag in a JSP file

Within my JSP, I have a string value stored in ${state.status.code} that I need to pass to a JavaScript function when a table element is clicked using onClick to trigger the showStatus function. Here is how I have attempted to achieve this: <c:set var= ...

Differences between count() and length() methods in Protractor

When it comes to determining the number of elements inside the ElementArrayFinder (which is the result of calling element.all()), you have two options according to the documentation: $$(".myclass").length, detailed here: This approach involves using ...

The jQuery toggle functionality seems to be malfunctioning

I have created a form that should toggle (hide and show) with the click of a button, but for some reason it's not working. Can someone please take a look at my code below and let me know what I'm doing wrong? $(document).ready(function () { ...

Issues with zDepth functionality in Material-UI (React.js) not being functional

Can anyone explain the concept of zDepth to me? I have a component with the following render method: render() { return ( <div> <AppBar zDepth={2} title="Some title" iconElementLeft={<IconButton onClick={this ...

Vue has detected an error during rendering: "TypeError: state.actionInfo.find is not a function"

Using vue.js's cli, I created a basic data register application. The application utilizes lookback.js api with vue cli. The application consists of three pages: show, add, and edit. While the show and add pages function correctly, issues arise when ...

What is the method for retrieving a value from my Node.js module once it has been modified by an asynchronous function?

Apologies, but as a beginner developer, I'm struggling to see how this relates directly to the questions already mentioned. I have no understanding of ajax and I'm unsure how to adapt the solutions provided to my own situation. Currently, I&apos ...

Creating a hierarchical JSON structure to populate a Handlebars template (HTML) for an iterative component, allowing for the display of three levels of interconnected

Currently, I am working on developing a mega menu component that involves three levels of content. Level 1 (L1): This level is displayed horizontally in a traditional navbar. When hovered over, it expands to reveal the mega menu. Level 2 (L2): These item ...

What is the best way to personalize the Window.Confirm() dialog in JavaScript?

var val= confirm("Are you sure to cancel?"); The code snippet above will display a popup with two choices - Ok and Cancel, with Ok being the default choice. Is there a way to make Cancel the default choice instead and switch the positions of the ...

The perfect way to override jest mocks that are specified in the "__mocks__" directory

Within the module fetchStuff, I have a mock function named registerAccount that is responsible for fetching data from an API. To test this mock function, I've created a mock file called __mocks__/fetchStuff.ts. Everything seems to be functioning corre ...

Change the display of the lightbox when clicked. Utilize Angular and JQuery for this functionality

Here is the code for a lightbox: <div id="light-box"> <div id="first"> ..... </div> //initially visible <div id="second"> ..... </div> //hidden - but displayed when button is clicked. </div> I want to add two button ...

AngularJS offers a function known as DataSource for managing data sources

During a recent project, I had to convert xml data to json and parse it for my app. One issue I encountered was related to the DataSource.get() function callback in the controller. After converting the xml data using a service, I stored the converted data ...