Sort function now accepts a limitless amount of arguments for sorting

We are tasked with creating a function that can take an unlimited number of arguments to sort an array by.

For example:

var data = [['John','London',35],
            ['Ricky','Kuala Lumpur',38],
            ['Ivan','Moscow,29]];

function arrangeOrder(a,b) {
 //Sort by field [0]
 if (a[0] > b[0]) return 1;
 if (a[0] < b[0]) return -1;

 //Sort by field [1]
 if (a[1] > b[1]) return 1;
 if (a[1] < b[1]) return -1;

 //Sort by field [2]
 if (a[2] > b[2]) return 1;
 if (a[2] < b[2]) return -1;
}

data.sort(arrangeOrder);

It works perfectly! However, the content of data and the number of fields can vary, as well as the fields and the number of fields by which the data needs to be sorted. So, what I need is a way to specify the function like this:

data.sort(arrangeOrder(1,3,6,9,2));

I have found a way to add ONE parameter:

function propComparator(prop) {
  return function(a,b){
    return a[prop] - b[prop];
  }
}
data.sort(propComparator(prop));

And also a way to handle an undefined number of arguments for the function using the arguments object:

function foo() {
  for (var i = 0; i < arguments.length; i++) {
    console.log(arguments[i]);
  }
}

But I am struggling to combine these techniques. It seems like it should be possible, but perhaps I lack the necessary skill.

NOTE: ES6 solutions are not compatible with my environment, so I require vanilla JavaScript! I appreciate any assistance I can get!

Answer №1

If you wish to define the specific order in which the indexes are passed as arguments, you can create a function that reads those arguments and generates a new function that can be used with the sort() method.

var data = [['Betty','London',35], 
            ['Xavier','Kuala Lumpur',38],
            ['Alan','Moscow',35]];


function sortFunc(){
    let args = arguments
    return function(a, b) {
        for (let i = 0; i < args.length; i++){
            if (a[args[i]] === b[args[i]]){
                continue
            }
            return a[args[i]] > b[args[i]] ? 1 : -1
        }
        return 0
    }
}

// Sort by age, then name, then city
let f = sortFunc(2, 0, 1)
data.sort(f)
console.log(data)

// Sort by age, then city, then name
f = sortFunc(2, 1, 0)
data.sort(f)
console.log(data)

// Can also be used with objects:
var data = [
    {name: "Mark", age:25, home: "Anchorage"},
    {name: "Mark", age:15, home: "New York"},
    {name: "John", age:25, home: "Aachen"},
    {name: "Alice", age:15, home: "Boston"}      
];

f = sortFunc("age", "home", "name")
data.sort(f)
console.log(data)

Answer №2

Implement a basic sorting algorithm using a for loop:

function compareValues(array1, array2) {
  for (var i = 0; i < array1.length; i++) {
    if (array1[i] > array2[i]) return 1;
    if (array1[i] < array2[i]) return -1;
  }
}

Answer №3

You have discovered the solution on your own [ I managed to figure out how to include a SINGLE parameter ]

var info =  [['Sara','Paris',27],
            ['Mike','New York',45],
            ['Elena','Madrid',32]];

function parameterSort(parameter) {
    return function(a,b){
        for (const x of parameter) {
            if ( a.hasOwnProperty(parameter[x]) && b.hasOwnProperty(parameter[x]) ) {
                if (a[ parameter[x] ] === b[ parameter[x] ]) continue;
                return a[ parameter[x] ] > b[ parameter[x] ] ? 1 : -1;
            } else
                continue;
        }
    }
}
var parameter = [2, 0, 1, 5, 1000];
info.sort(parameterSort(parameter));

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

Dividing Faces with Lengthy Edges in three.js into Two Separate Faces

I am currently working on a script that involves splitting overly long edges of faces into two separate faces instead of one large face. The final result is exported to a .obj file. Although the geometry reduction works fine, I have noticed some issues a ...

Retrieve pixel information upon touch in an Appcelerator Titanium application on Android or iPhone

Can pixel level data of an image view be accessed using Titanium Mobile on Android/iPhone? ...

Identifying a Resizable Div that Preserves its Aspect Ratio During Resizing

Below is the HTML code snippet I'm working with: <div id="myid_templates_editor_text_1" class="myid_templates_editor_element myid_templates_editor_text ui-resizable ui-draggable" style="width: 126.79999999999998px; height: 110px; position: absolut ...

Validate the date selected in a dropdown menu using JavaScript

I'm still relatively new to Javascript, just working my way through some tutorials. I have three select boxes in my HTML form as shown below. HTML Form: <table> <form id="enrolment" name="enrolment" onsubmit="return datevalidate();" action ...

angularjs issue with $setPrestine function not providing reliable results

I have encountered an issue with the login form code. Initially, I am able to reset the form fields and error messages successfully on the first attempt (both success and failure scenarios work). However, on the second try, I am unable to reset the form fi ...

Choosing Nested TypeScript Type Generics within an Array

I need help with extracting a specific subset of data from a GraphQL query response. type Maybe<T> = T | null ... export type DealFragmentFragment = { __typename: "Deal" } & Pick< Deal, "id" | "registeringStateEnum" | "status" | "offerS ...

Testing the functionality of an Express.js application through unit testing

I'm currently working on adding unit tests for a module where I need to ensure that app.use is called with / and the appropriate handler this.express.static('www/html'), as well as verifying that app.listen is being called with the correct p ...

"Exploring the Magic of Jquery's Fadein() Animation

i have experience with writing code for a jQuery fadein effect. imagine I have an HTML element stored in a variable, like this: var sHtml="<div>Other content</<div><div id='frm'>hello</<div>"; modal.load(jQuery(sHt ...

The added class is not being successfully applied to the ClassList

I'm currently working on a page where I want the colors of a button and the background to switch when the button is clicked. document.querySelector("body.light").classList.toggle("dark"); document.querySelector("button.dark").classList.toggle("light" ...

Using JQuery to search for and remove the id number that has been clicked from a specific value

I am in need of assistance with deleting the clicked id number from an input value using jQuery. I am unsure of how to proceed with this task and would appreciate some guidance. To simplify my request, let me explain what I am trying to accomplish. Take ...

Incorporating website data into my JavaScript code

I lack experience in extracting data from websites, but I'm interested in learning how to utilize data from: . I believe this data is in the form of an array and I want to loop through it to find an item with the name "example" and gather additional i ...

Extract information from an array located inside a nested object

My aim is to calculate the length of the skills array for each user individually. To begin, I have this JSON data: const txt = `{ "Alex": { "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" da ...

My ReactNative Android application is experiencing significant lag, is there anyone who can assist me in resolving this issue?

Currently, I'm tackling a reactnative android app project and have noticed a significant drop in performance. Unfortunately, I am clueless about the root cause of this issue. Could it be related to the navigator or are there other underlying factors a ...

extracting an empty value from this variable

When I click on an anchor tag using this operator, the value appears blank. I have multiple divs with the same class, so I used the .each() function, but I can't figure out where I'm going wrong. The desired output is that when I click on one of ...

Enhancing the ShaderMaterial attribute in three.js

Exploring the three.js tutorial on shaders, we discover a technique for updating uniform values of a ShaderMaterial: var attributes = { displacement: { type: 'f', // a float value: [] // an empty array } }; var uniforms = { amplitu ...

Internet Explorer 10 not triggering the 'input' event when selecting an option from the datalist

Within this particular scenario, there is an input field paired with a corresponding datalist element. My aim is to develop JavaScript code that actively listens for when a user chooses an item from the list. Most resources suggest utilizing the "input" ev ...

Utilizing AJAX to dynamically load file references and embed iframes

Is the use of multiple iframes on a website impacting its loading speed? Also, regarding AJAX, let's say I have two JSP pages. The first one contains an AJAX call to the second JSP page. Both pages have JavaScript functions with the same name, let&apo ...

Transferring data between jQuery and other global JavaScript variables

I'm facing a challenge when trying to make functions I created in jQuery access JavaScript values defined elsewhere. For instance, I have a function set within my jQuery code. var parentImg = ''; //global variable. $(document).change(funct ...

What is the method for shifting content as the window is resized to ensure it remains in its original position?

My page features a grid with three div elements. Each div is the size of the viewport, resulting in only one div being visible at a time, while the other two remain outside the view. This makes the grid three times larger than the viewport. When resizing ...

Node.js now supports ES6 imports using the `--experimental-modules` flag,

Experimenting with ES6 imports in node using the -experimental-modules flag. Here are the steps: mkdir testfolder cd testfolder npm init npm i --save testing-library touch script.mjs Next, add the following code to script.mjs: import { test1, test2, tes ...