Sort the array of objects based on the nested attribute

I am facing a challenge in ordering an array based on a nested object. The array contains information about objects on a timeline and I would like to sort it by the start position defined within nested arrays. Currently, I am able to iterate through the array using lines[0].events[0].start

Below is the structure of the array:

timelines = [
    {
    name: 'obj1',
        data: { id : 'obj1-guid' },
        lines: [{
          events: [{
            name: 'animation1',
            data : { id : 'animation1-guid' },
            start : 100,
            duration : 200
          }]
        }],
        video_url: 'url',
    },
    {
    name: 'obj2',
        data: { id : 'obj2-guid' },
        lines: [{
          events: [{
            name: 'animation1',
            data : { id : 'animation1-guid' },
            start : 4,
            duration : 200
          }]
        }],
        video_url: 'url',
    },
    {
    name: 'obj3',
        data: { id : 'obj3-guid' },
        lines: [{
          events: [{
            name: 'animation1',
            data : { id : 'animation1-guid' },
            start : 56,
            duration : 200
          }]
        }],
        video_url: 'url',
    },

];

I have attempted to write a sorting function as follows:

function sorting(json_object, key_to_sort_by) {
          function sortByKey(a, b) {
              var x = a[key_to_sort_by];
              var y = b[key_to_sort_by];
              return ((x < y) ? -1 : ((x > y) ? 1 : 0));
          }
          json_object.sort(sortByKey);
        }

 timelines = sorting(timelines, 'lines[0].events[0].start');

However, this function is not functioning as expected.

Answer №1

Just your typical arrange:

sequences = [
    {
    name: 'obj1',
        data: { id : 'obj1-guid' },
        lines: [{
          events: [{
            name: 'action1',
            data : { id : 'action1-guid' },
            start : 100,
            duration : 200
          }]
        }],
        video_url: 'url',
    },
    {
    name: 'obj2',
        data: { id : 'obj2-guid' },
        lines: [{
          events: [{
            name: 'action1',
            data : { id : 'action1-guid' },
            start : 4,
            duration : 200
          }]
        }],
        video_url: 'url',
    },
    {
    name: 'obj3',
        data: { id : 'obj3-guid' },
        lines: [{
          events: [{
            name: 'action1',
            data : { id : 'action1-guid' },
            start : 56,
            duration : 200
          }]
        }],
        video_url: 'url',
    },

];

const result = sequences.sort((first, second) => first.lines[0].events[0].start - second.lines[0].events[0].start);

console.log(result)

Answer №2

To implement custom sorting in JavaScript, you can pass a function to the [].sort method.

For ascending sorting order:

timelines.sort( function(a, b){ 
    return a.lines[0].events[0].start - b.lines[0].events[0].start
})

For descending sorting order:

timelines.sort( function(a, b){ 
    return b.lines[0].events[0].start - a.lines[0].events[0].start
})

You can find more information about how the comparison function works on MDN.

If compareFunction is provided, the array elements will be sorted based on the return value of the comparison function. When comparing two elements a and b:

  • If compareFunction(a, b) is less than 0, a will be placed before b in the sorted array.
  • If compareFunction(a, b) returns 0, a and b will maintain their relative order but might change positions with other elements.
  • If compareFunction(a, b) is greater than 0, b will be placed before a in the sorted array.
  • The comparison function should always return consistent results for a specific pair of elements a and b. Inconsistent results may lead to undefined sort behavior.

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

Creating arrays of structures of arrays in a dynamic way

Apologies for bringing up this issue again. I see that there are similar problems discussed here, but I am still struggling to understand what I'm doing wrong. My task is to create a simple database for student information, using dynamic memory alloc ...

Unable to iterate through Ajax calls using For Loop when onChange event occurs

I'm struggling with looping the OnChange method using an AJAX call, but for some reason, it's not working as expected. for (let index = 0; index < 300; index++) { $('#txtLini'+[index]).on('change', function() { ...

Begin the process of setting up PDF.js on the website

I've been attempting to incorporate PDF.js into my website, but I'm struggling to do it correctly. When I try to display the PDF file on the screen, I encounter this issue: https://i.sstatic.net/aixrP.png Although I can't see the PDF file ...

Creating an axios URL using Vue data results in receiving the value of undefined

I'm currently experimenting with axios to retrieve data from openweathermap. I've been working on constructing the URL by utilizing various methods to extract latitude and longitude from the user's browser, followed by a function call to pie ...

Changing an Array of DaysOfWeek to an Enum: A Simple Guide

I am receiving a WeeklyPattern with DaysOfTheWeek from EWS. It is stored in an Array and can include one day or multiple days. There is an Enum called DayOfWeekMask that I need to use to convert the Array values into the Enum format. If the WeeklyPattern ...

I encountered a data discrepancy while attempting to link up with a weather API

This is my debut app venture utilizing node.js and express for the first time. The concept behind this basic application involves connecting to an external API to retrieve temperature data, while also allowing users to input their zip code and feelings whi ...

I can't figure out why I'm receiving a TypeError saying that choices.map is not a function

I'm currently working on mapping items (choices) in an array to a <select> field using <MenuItem>. I'm very close, but I keep encountering a TypeError choices.map is not a function error. const useStyles = makeStyles(theme => ({ ...

converting JSON to date format in angular

.controller('feedCtrl', ['$scope', '$http', function($scope, $http) { $http.get('items.json').then(function(response) { $scope.items = response.data; $scope.user = localStorage.getItem("glittrLoggedin"); ...

Error message "$injector:unpr" occurs in the run method of AngularJS after minification process

I've encountered an issue with angular-xeditable on my Angular app. While it functions properly in the development environment, I'm facing an error in production when all JS files are minified: Uncaught Error: [$injector:strictdi] http://errors. ...

What could be causing my React Router to display empty pages?

I've been working with the latest version of create-react-app and have been struggling to display the pages within my app. I've tried both functional components and class-based components, but nothing seems to work. I've wrapped the content ...

What repercussions come from failing to implement an event handler for 'data' events in post requests?

If you take a look at the response provided by Casey Chu (posted on Nov30'10) in this particular question: How do you extract POST data in Node.js? You'll find that he is handling 'data' events to assemble the request body. The code sn ...

Tips on managing ajaxStart and ajaxStop events the Angular2 way

I am seeking a way to trigger events similar to JQuery's ajaxStart and ajaxStop. While I found a partial solution on how to set default HTTP headers in Angular 2 here, I have managed to handle the ajaxStart event for now. Does anyone have any soluti ...

Optimize Page Speed by Delaying the Loading of Slideshow Images

My main issue with reducing my pagespeed is the slideshow I have implemented. I currently have 17 rather large images in the slideshow, but for simplicity, I will only show the code for 3 images below. I am trying to find a way to load the first image as a ...

The collision of two OnClick events results in the disruption of the proper execution of the first event

I have been working on integrating a new jQuery toggle function into existing code. The goal is to show/hide the form_fields_con div below with an onclick event. The issue arises because the form_fields_con div also contains AJAX functionality triggered b ...

Discovering nearby intersections within 2 sets of arrays

Imagine having these two arrays: var a = [126, 619, 4192, 753, 901]; var b = [413, 628, 131, 3563, 19]; Is there a way to identify elements in both arrays that are close to each other by a certain percentage? Let's say we have the following functio ...

"Emulate the social sharing capabilities of CNET with interactive share

I remember a while ago, CNET had these amazing Social Share buttons that, when clicked, would reveal a "dropdown box" with the social network share dialog. Does anyone know how they achieved that? I've searched but couldn't find any information ...

The process of enabling NPM packages for use with ES6 and ECMAScript

Currently, I am working on developing an NPM package using TypeScript. My main concern is how to ensure that this package can be made available for both ES and Node modules. To achieve this, I have configured Rollup along with a few settings: rollup.conf ...

having difficulty preserving the edited HTML document with JSoup and Java

I am facing an issue with modifying and saving changes to an existing HTML file. I can make modifications, but when it comes to saving the changes back to the HTML file, I encounter difficulties. https://i.sstatic.net/CRhUV.jpg The specific modification ...

Inquiries about ngshow and the scope concept

I have a question about using AngularJS. I have multiple sections and only want to display one at a time using <section ng-show="section6_us"> </section> and <section ng-show="section7_us"> </section>. My scope has many variables. ...

I am unable to load any HTML files in my VueJS iframe, except for the index.html located in the public

Within the template of my vue component, I am utilizing the following code: <iframe width="1000vw" height="600vh" src="../../public/myHtmlFile.html"></iframe> Unfortunately, the file specified in the src attribut ...