Tips for sorting JSON data based on multiple attributes

http://jsfiddle.net/dy8w8r7d/

How can JSON data be sorted based on two attributes? This code snippet currently only sorts by Episode..

Purpose: arrange the data by sorting on Episode in ascending order, followed by sorting on Sequence in ascending order

var data = [ { ArticleId: 2, Episode: 1, Type: 0, Sequence: 0 },
  { ArticleId: 1, Episode: 1, Type: 0, Sequence: 1 },
  { ArticleId: 3, Episode: 2, Type: 0, Sequence: 0 },
  { ArticleId: 4, Episode: 2, Type: 0, Sequence: 1 } ];

var data = [ { ArticleId: 2, Episode: 1, Type: 0, Sequence: 1 },
  { ArticleId: 1, Episode: 2, Type: 0, Sequence: 0 },
  { ArticleId: 3, Episode: 1, Type: 0, Sequence: 0 },
  { ArticleId: 4, Episode: 2, Type: 0, Sequence: 1 } ];


function compareEpisodeSequence(a,b) {
  if (a.Sequence < b.Sequence)
    return -1;
  if (a.Sequence > b.Sequence)
    return 1;
  return 0;
}
data.sort(compareEpisodeSequence);

console.log(data);

Answer №1

Here is a code snippet that should meet your requirements:

function checkEpisodeSequence(a,b) {
  if (a.Episode < b.Episode) return -1;
  if (a.Episode > b.Episode) return 1;
  if (a.Sequence < b.Sequence) return -1;
  if (a.Sequence > b.Sequence) return 1;
  return 0;
}

If the Episodes are the same, then it will compare the Sequences to determine the order.

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

Discover the power of jQuery: Incorporating unique dynamic inputs within dynamic divs

I have a piece of PHP code that looks like this: foreach ($questions as $q){ foreach ($answers as $a) { echo '<input type="text" id="'.$a['question_id'].'_'.$a['id_answer'].'" value="'.$ ...

Retrieving JSON data from a URL using AngularJS's HTTP get request

I am facing an issue with this code where I am trying to retrieve JSON data from my ASP.NET Web API using AngularJS. However, I am unable to fetch the data successfully. Below is the code snippet: <!DOCTYPE html> <html ng-app="myapp"> <he ...

Distinguishing Response Headers in XMLHttpRequest and jQuery AJAX FunctionUniqueness:

Hello, I'm facing an issue that is not a duplicate. Here is the code snippet: var data = {'userId': window.cookie.get('userId'), 'sessionId': window.cookie.get('sessionId')} $.post(window.DbUrl + '/t ...

The get method is functional, however, the post method is not working as expected in Zap

I'm currently using zapworks studio to create an AR experience. This involves using Z.ajax for ajax calls, including GET and POST requests. For hosting couchdb, I've opted for smileupps due to their free hosting service. The CORS configuration is ...

Creating a chart with multiple series in canvas js through looping

I'm currently working on creating a multi-series chart using Canvasjs. I've encountered an issue where I can't include a loop inside the dataPoints and have had to manually code everything. Is there a way to utilize for loops in this scenari ...

The JavaScript function prints the variable using `console.log(var)`, however, it does not assign `var2` to

I've been following a tutorial on implementing push notifications in VueJS from this link. After running the register function on the created hook, I encountered an issue: register() { if ("serviceWorker" in navigator && "PushManager" in window ...

Display modal popup only once the dropdown has been validated, with the validation focusing on criteria other than the dropdown itself

Looking for a way to validate dropdown values. Popup should only show if the dropdown values are selected; otherwise, the popup should remain hidden. Below is the code snippet: <div class="main-search-input-item location"> ...

What is the method for performing a MongoDB left join while retaining documents that do not have a match on the right side?

Forgive my newness to this topic, but I am attempting a left outer join in MongoDB/NodeJS and seeking assistance. My goal is to retrieve all matching documents from the left table, even if they do not have a match on the right. Within my database, I have a ...

SBJsonParser tried to use an invalid method with instance 0x6695330, resulting in an NSInvalidArgumentException error

Encountered an issue while developing a login view for my iPhone app. The error message reads: 'NSInvalidArgumentException', reason: '-[SBJsonParser objectWithString:error:]: unrecognized selector sent to instance 0x6695330' The l ...

After refreshing the page, the local storage does not appear

I've been struggling to get it working for hours with no luck. After submitting the form, I create local storage values for name, surname, and email so that they can be automatically filled in the form next time without requiring the user to retype th ...

Next.js components do not alter the attributes of the div element

I am encountering a problem with nextjs/reactjs. I have two tsx files: index.tsx and customAlert.tsx. The issue that I am facing is that the alert does not change color even though the CSS classes are being added to the alert HTML element. Tailwind is my c ...

Implementing proper data return in MVC4 through an Ajax call

When using ajax to call an action in a controller, the code may result like this: $.ajax({ type: "POST", url: "getUserInfo.json", data: "", success: function (data) { if (data.resultInfo.resu ...

Is your idTabs design in need of some sprucing up

Just stumbled upon idTabs and trying to implement a basic one on my server. I've taken the code from the 'Usual' page, included the plugin file and jQuery, but all I'm seeing is... - Tab 1 - Tab 2 - Tab 3 This is tab 1. Seems like it& ...

Problem encountered when using the Mongoose find() method with the exec() function

Could you please clarify why the code snippet below is returning audiences instead of an empty array? return Audience.find() .exec((err, audiences) => { if (err) return errorHandler.handle('audienceService', err); return Promise.re ...

The OrbitControls function is not able to be instantiated as a constructor

I've been working on creating a WebVR environment for the past week using Three.js, but I'm having trouble getting the VR controls to function correctly. Here are some of the things I've tried: 1. Adding packages in my node_modules and imp ...

Tips for utilizing multiple CSS styles in JavaScript

My goal is to apply multiple CSS styles to a button with the id of name_button. Below is the JavaScript code I have written: var name_button = document.getElementById('name_button'); name_button.style.display = 'block'; name_button.st ...

Pairing a removal request with a JSON entity

I am currently working on a project where I need to delete a specific JSON object from a JSON file once its values are displayed in a form using the AJAX Delete function. In order to achieve this, I have set up a route in Express for the JSON file as shown ...

Failure in Deserializing JSON Sets/Lists with Jackson and Spring 3.0

Currently, I am facing an issue with deserializing POJO objects that have sets in them. For example: class C { Set<SomeObject> set; ... } When using Jackson 1.8 auto mapping, all properties are retrieved correctly. However, when trying to ...

AngularJS right-click menu

I need a context-menu directive that can provide information on the clicked element for proper reaction. Although I experimented with this module, I'm facing an issue in uniquely identifying the clicked element. This is hindering my ability to apply ...

Activate Button upon Textbox/Combobox/RadDatePicker Modification through JavaScript

On my ASP.NET form, I have various input elements including textboxes, dropdowns, date pickers, and update buttons. My goal is to enable the update button whenever a user makes a change in any of these fields. To achieve this, I applied a specific CSS cla ...