Sorting an array of objects that have deep nested properties can be achieved using the lodash orderBy method

Here is a suggestion for using the orderBy function from lodash in a recommended way:

 const data = _.orderBy(array_of_objects, ['type','name'], ['asc', 'desc']); - instead of keys 

Is there a way to accomplish sorting based on deep values by passing key paths as string arrays like this ['type.id','name.entry'] rather than object keys?

The goal is to have an array sorted according to deeply nested properties.

 const data = _.orderBy(array_of_objects, ['type.id','name.entry'], ['asc', 'desc']); - instead of keys 

I am curious about this possibility because lodash provides access to an object's deep properties using _.get() as demonstrated below.

_.get(object, 'a[0].b.c');
// => 3

This makes me wonder if it can be achieved with _.orderBy() as well.

NB If there is a way to do this in vanilla JavaScript, please advise accordingly.

In my current scenario, I am facing difficulty sorting by multiple deeply nested props ['type.id','name.entry'], where only one seems to work at a time.

If achieving this directly is not possible, suggestions on how to sort an array of objects with deeply nested properties based on multiple deeply nested props passed as string paths would be highly appreciated.

Answer №1

The orderBy function in Lodash version 4.x does support a callback, enabling you to order data based on multiple attributes by providing a list of functions. Here's how you can achieve single and multiple attribute ordering:

// for single attribute ordering
const orderedData = _.orderBy(arrayOfObject, item => item.id, ['desc']);

// for multiple attribute ordering
const orderedData = _.orderBy(arrayOfObject, [
  item => item.id,
  item => item.entry,
], ['desc', 'asc']);

If you need to sort based on a nested attribute within each object, you can use the following example:

const items = [
  {
    id: 1,
    entry: 'a',
    nested: { val: 5 },
  },
  {
    id: 5,
    entry: 'five',
    nested: { val: 1 },
  },
  {
    id: 3,
    entry: 'three',
    nested: { val: 2 },
  },
  {
    id: 2,
    entry: 'two',
    nested: { val: 3 },
  },
  {
    id: 4,
    entry: 'four',
    nested: { val: 4 },
  },
];


const nestedValueComparator = item => _.get(item, 'nested.val');

const nestedData = _.orderBy(items, nestedValueComparator, ['asc']);

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

Using JavaScript Arrays to Make Labels in Chart.js

I am currently working with Chart.js and have a JavaScript array containing values that look like this: var obj = JSON.parse('{"0":"8.4113","2":"9.5231","3":"9.0655","4":"7.8400"}'); I am passing the "obj" array to my Chart.js, filling out the ...

What is the best way to retrieve specific JSON data from an array in JavaScript using jQuery, especially when the property is

Forgive me if this question seems basic, I am new to learning javascript. I am currently working on a school project that involves using the holiday API. When querying with just the country and year, the JSON data I receive looks like the example below. ...

Element vanishing post JSON parsing

I have encountered an intriguing issue: I have developed an HTML/JS project that extracts information using XMLHttpRequest from the Scratch website. The main objective is to allow users to input their username and view their profile description on Scratc ...

jQuery opacity transition not functioning properly while all other animations are working fine

I've encountered quite a peculiar issue: Using jQuery v11 on the latest version of Chrome localhost, I can successfully apply jQuery.animate() to various elements and features on my website, including opacity. However, there is one particular element ...

Incorporating Paged.JS functionality into a React/JS web application

My attempt to showcase my html page using paged.js in a react project has hit a snag. The html loads perfectly when accessed from local host (not via npm start, but the live server extension on vscode). However, following the steps outlined on this website ...

Adding roles in ReactJS: A step-by-step guide

I am looking to enhance the admin's roles upon login to enable the creation of new users. Unfortunately, I am uncertain on how to add these roles and make them functional. Below is the code I have: Login.js class Login extends Component { cons ...

Attempting to incorporate a hover effect into this piece of JavaScript code

Hello, I've been trying to implement a mouse-over effect into this code but have not had much luck. Any assistance would be greatly appreciated. If you require additional information, please let me know. The issue I am facing is that when I hover ove ...

Hovers and click effects for navigating through images

The website I'm currently working on is stipz.50webs.com. p.s. HOME functionality is not active at the moment. Having successfully implemented the onhover and onmouseout features, my next goal is to enhance the navigation effects for each div/img so ...

Converting JSON data to HTML using Handlebars

Can you assist me in transforming the following JSON data into a table with 3 columns: property name, property source, and property value? "result": { "total": 100, "config": { "propName1": { "source": "propsrc1", ...

Why is Vue Router Navigation Guard throwing an error about exceeding the maximum call stack size?

Encountering a recurring issue of maximum stack size exceeded while implementing the following code for vue router navigation guards per-route: import state from "../vuex-store/state.js"; import Editor from "../views/Editor"; const routes = [ { ...

iOS does not support webkit-transform functionality

I've been working on incorporating a navigation drawer into my Sencha Touch app by following this article. The animation mentioned in the article utilizes webkit-transform, which functions perfectly on Chrome and Android devices, but seems to be causi ...

Help me figure out how to independently toggle submenus on my navbar by utilizing the Vue.js composition API

I am currently working on developing a navbar using the Vue.js composition API. My primary objective is to toggle the submenus when a user clicks on them. However, since I am iterating through an object to display the submenus, I am faced with the challeng ...

Identify changes in attributes on elements that are updated automatically

On my webpage, I want to have two select boxes that are connected so their values always match. Here's an example: Imagine a page with two selects: <select class="myselector"> <option value='1'>1 <br> < ...

Nodejs application encountering a problem with the findUser method in Active Directory

I have encountered an issue while using the activedirectory npm package with Nodejs v16.18.1. The code snippet below is used for authentication and finding user details: Could someone please assist with this? async authUserActiveDirectory(usernameAD: stri ...

Execute PHP code upon JavaScript confirmation

Whenever I update the status, an email is automatically sent. The issue is that it sends the email again if any other field is updated as well. What I want is a confirmation prompt before sending the email. I tried using AJAX to handle this, but even thoug ...

What is the reason for the faster deletion performance of objects compared to arrays when using the splice method

Curious about the speed variations between arrays and objects, I decided to conduct a test involving filling, accessing, and deleting 100,000 items from both. Surprisingly, accessing and filling the array showed minimal difference with only about ~3ms gap. ...

Exploring the world of CSS: accessing style attributes using JavaScript

So I created a basic HTML file with a div and linked it to a CSS file for styling: HTML : <html> <head> <title>Simple Movement</title> <meta charset="UTF-8"> <link rel="stylesheet" type=&qu ...

What is the best way to structure Vue.js components for optimal organization?

Imagine having an index page called index.vue consisting of various components like this: index.vue <template> <div> <component-1 /> <section class="section-1"> <div class="container section-container"> <com ...

Gain a comprehensive understanding of the JavaScript syntax utilized throughout the code

I stumbled upon this JavaScript code that enables asynchronous file uploads, but there are certain parts of it that I'm struggling to grasp. Any insights or explanations would be greatly appreciated - many thanks in advance. // Utilizing Ajax for Fil ...

Implementing tether in webpack: A step-by-step guide

My webpack application, which I am using with Laravel Elixir, includes a 'bootstrap.js' file for initializing all libraries. Here is the content of the file: window._ = require('lodash'); /** * We'll load jQuery and the Bootstra ...