Emulating the sorting functions in Excel, including "sort by" and "then by" actions

Is there a way to replicate Excel's sorting in JavaScript?

Imagine I have an array with the following items:

[6,0.75]
[6,0.81]
[9,0.75]
[4,0.20]

Sorting them by the first key is straightforward, but how can we achieve "then by" sorting? If we apply a descending order to the first key and then to the second key, Excel would provide us with the following result:

[9,0.75]
[6,0.81]
[6,0.75]
[4,0.20]

Answer №1

While there are simpler methods available for this specific example, in a more general scenario you have the option to utilize a function with the sort method to compare each pair of values in a defined order. (View example on jsfiddle)

var arr1 = [[6, 0.75], [6, 0.81], [9, 0.75], [4, 0.20]],
    arr2 = [[6, 0.75], [6, 0.81], [9, 0.75], [4, 0.20]],
people = [{name: 'Jim', age: 40}, {name: 'Sally', age: 35},
          {name: 'Tim', age: 20}, {name: 'Jim', age: 72}];

function orderedComparison(indices) {
    return function(a, b) {
        for (var i = 0; i < indices.length; i++) {
            if (a[indices[i]] > b[indices[i]]) return 1;
            if (a[indices[i]] < b[indices[i]]) return -1;
            // (if a == b, check next index)
        }
    }
}
// sorting by first item in each pair followed by second
arr1.sort(orderedComparison([0, 1]));
console.log(arr1);
// sorting by second item then first
arr2.sort(orderedComparison([1, 0]));
console.log(arr2); 
people.sort(orderedComparison(['name', 'age']));
console.log(people);​

It is important to note that simply sorting by the lower-priority key first and then the higher-priority key may work in some cases but is not always guaranteed.

arr1.sort(function(a, b) {return a[1] - b[1]});
arr1.sort(function(a, b) {return a[0] - b[0]});

Answer №2

To achieve the same functionality, you can adjust the scale of each subindex to ensure that their sizes do not overlap. Then, perform a standard comparison using the Array.sort(); method.

You can see this concept in action on this jsfiddle: http://jsfiddle.net/Pg4Lt/7/

Tip: If you're unfamiliar with the term magnitudes, it refers to the exponent of ten when representing numbers in scientific notation. For example, 6 = 6 * 10^0 => The magnitude of 6 is zero.

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

Populate Jquery datatables programmatically

After implementing the Jquery Datatables plugin, I initially had hardcoded content in the table. However, I made some modifications to dynamically populate the table with fetched data. While this change worked fine, I encountered issues with the search f ...

Discovering the hovered time value on an input range slider

I realize that my question may have been a bit unclear, so I will provide a detailed explanation here. I am currently working on creating a simple video player for a webpage. I am using an input range element to display the file duration and current time, ...

The Gridsome website deployed on Netlify seems to be experiencing some issues. When clicking on links, the pages are not loading properly despite

After deploying my site on Netlify, I encountered an issue where the URL updates when clicking on links on the landing page, but the content does not show unless the page is refreshed. Interestingly, this issue does not occur on my local development server ...

Searching for text using JQuery autocomplete feature with results fetched from an external source

I am currently working on integrating an input field with autocomplete functionality using the Google Books API to suggest book titles based on user input. My framework of choice for this implementation is Django. So far, I have managed to achieve the fol ...

Troubleshoot: Dropdown menu in Materialize not functioning (menu fails to drop down

I am currently incorporating Materialize to create a dropdown button in my navigation bar. However, I am facing an issue where nothing happens when the button is clicked. Here is a snippet of my code: <head> <meta charset="UTF-8"> <!-- ...

Guide to configuring the API key within the Stampery API.JS script

Currently, I'm in the process of configuring Stampery but I'm facing difficulty locating where to insert the string API key within the API.JS file. The documentation mentions setting the STAMPERY_TOKEN as the API key, but I'm unsure how to p ...

Enhance the annotation of JS types for arguments with default values

Currently, I am working within a code base that predominantly uses JS files, rather than TS. However, I have decided to incorporate tsc for type validation. In TypeScript, one method of inferring types for arguments is based on default values. For example ...

React-NextJS encountered an error: TypeError, it cannot read the property 'taste' because it is undefined

Recently, I've been encountering an issue with NextJS that keeps throwing the error message: TypeError: Cannot read property 'taste' of undefined. It's quite frustrating as sometimes it displays the expected output but most of the time ...

A guide on updating the color of a Button component (Material UI) when dynamically disabling it

In a React table, I have a button that is disabled based on the value in an adjacent column. For example, if the value in the adjacent column is "Claimed", the button is disabled. However, if the value is "Failed" or blank, the button can be clicked. Curre ...

Merging two arrays in Typescript and incrementing the quantity if they share the same identifier

I am currently working on my Angular 8 project and I am facing a challenge with merging two arrays into one while also increasing the quantity if they share the same value in the object. Despite several attempts, I have not been able to achieve the desired ...

Utilizing camera perspective for coordinate system in Three.js

This question may seem basic, but I'm having trouble grasping it. I'm working on a scene using Three.js and the camera setup is as follows: var camera = new THREE.PerspectiveCamera( 85, window.innerWidth/window.innerHeight, 0.1, 1000 ); camera. ...

Discover how to retrieve the calculated percentage within CSS with the assistance of jQuery specifically designed for Webkit

I'm currently working on a simple sliding animation. However, the div that slides in is utilizing percentages for its width and right positioning. The issue arises specifically in Webkit browsers. When using jQuery to retrieve the value, it returns t ...

Using Facebook authentication in React Native

Currently developing a React Native app and aiming to incorporate Facebook login functionality. The back-end logic for user authentication is handled by an API in Node.js. Utilizing passport.js to enable users to log in using either Facebook or Email cre ...

Remove a child node from its parent node in real-time

Currently, I am working on a project that involves adding and removing items as needed. The user interface can be seen in the image provided below: https://i.sstatic.net/Qhy2t.png Workflow: When the add icon is clicked, a new column is added for assignme ...

How can I determine the size of a double * array in C++?

Is there a method to determine the size of a double *positions[2] array once it has been declared? Can a sizeof function be used for this purpose? I attempted an example, but the size returned was not 4 http://ideone.com/vp3tJz ...

Have developers created an event trigger for when google maps controls finish loading?

While I am aware of the tilesloaded event, it appears that the controls load after this event. My goal is to use jQuery to retrieve the controls, but I am struggling to identify the appropriate event to listen for. ...

When iterating over objects in JavaScript, the loop may return undefined, while using Lodash's map

After encountering an issue with a JavaScript loop where the value was returning as null upon completion, I decided to try using lodash for the same purpose and it successfully returned the result. This is what I attempted: JavaScript: const jsRows = Ob ...

Iterate through the form fields and save the information into an object

I am attempting to create a JavaScript object by looping through form inputs. const data = {}; // loop through each input found in form $('#form_name').filter(':input').each(function() { const $id = $(this).attr('id'); c ...

What are some techniques to maintain consistent color blending while orbiting a three-dimensional object in Three.js?

Is there a way to maintain consistent colors on a rectangle while rotating around it? The colors currently change based on the normals when using the orbitcontrols library addon. Check out the jsfiddle and code below: /* import * as THREE from 'https ...

Collapse the hamburger menu upon clicking on a link in the mobile menu

Whenever I click on a menu item, the page loads but the menu remains open. This JSX code represents the Mobile Menu: const MobileMenu = () => { const navigation = [ { link: '/applications', text: 'Applications' }, { link ...