Sorting arrays in JavaScript based on dynamic columns

My current JavaScript Array Sorting code gets the job done, but it feels inefficient.

For example, I have an array of objects structured like this:

dummyData = [];
dummyData.push({ col01:"aa", col02:"ac", col03:"ab" });
dummyData.push({ col01:"ab", col02:"ab", col03:"ac" });
dummyData.push({ col01:"ac", col02:"aa", col03:"aa" });

To sort this array based on col01, I use the following function:

function f_sort_col01(dataArg) {

   dataArg.sort(function(res01, res02) {
      var arg01 = res01.col01.toLowerCase();
      var arg02 = res02.col01.toLowerCase();
      if(arg01 < arg02) { return -1; }
      if(arg01 > arg02) { return 1; }
      return 0;
   });

   return dataArg;

}

While this approach works, it requires creating a new function for each column we want to sort on, like f_sort_col02 for col02:

function f_sort_col02(dataArg) {

   dataArg.sort(function(res01, res02) {
      var arg01 = res01.col02.toLowerCase();
      var arg02 = res02.col02.toLowerCase();
      if(arg01 < arg02) { return -1; }
      if(arg01 > arg02) { return 1; }
      return 0;
   });

   return dataArg;

}

It would be more efficient if we could generalize the sorting function to accept the column name as a parameter, like this:

function f_sort(dataArg, colName) {

   dataArg.sort(function(res01, res02) {
      var arg01 = res01[colName].toLowerCase();
      var arg02 = res02[colName].toLowerCase();
      if(arg01 < arg02) { return -1; }
      if(arg01 > arg02) { return 1; }
      return 0;
   });

   return dataArg;

}

This way, we can specify the column name when calling the function, making the sorting process more flexible.

Answer №1

For sorting data, use square brackets as shown below:

function sortData(dataArr, columnName) {

   dataArr.sort(function(item1, item2) {
      var value1 = item1[columnName].toLowerCase();
      var value2 = item2[columnName].toLowerCase();
      if(value1 < value2) { return -1; }
      if(value1 > value2) { return 1; }
      return 0;
   });
   return dataArr;
}

Answer №2

To change your approach, you could consider implementing a closure that encapsulates the desired key.

function sortDataBy(key) {
    return function (item1, item2) {
        return item1[key].toLowerCase().localeCompare(item2[key].toLowerCase());
    };
}

var data = [{ col01: "aa", col02: "ac", col03: "ab" }, { col01: "ab", col02: "ab", col03: "ac" }, { col01: "ac", col02: "aa", col03: "aa" }];

console.log(data.sort(sortDataBy('col01')));
console.log(data.sort(sortDataBy('col02')));
console.log(data.sort(sortDataBy('col03')));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №3

Try using [colName] in place of .colName

function f_sort(dataArg, colName) {

   dataArg.sort(function(res01, res02) {
      var arg01 = res01[colName].toLowerCase();
      var arg02 = res02[colName].toLowerCase();
      if(arg01 < arg02) { return -1; }
      if(arg01 > arg02) { return 1; }
      return 0;
   });

   return dataArg;

}

Answer №4

Utilizing square bracket notation:

retrieve the lowercase value of res01[colName] and assign it to arg01
retrieve the lowercase value of res02[colName] and assign it to arg02

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 an object in JavaScript using variables

Is it possible to create an object with keys coming from a variable parameter? Let's say 'prod_id' holds a value, and I want to create an object with key 'prod_id' and value 1. Can this be achieved? If so, how? Thank you! var cart ...

Aggregating various database entries into an array

I want to retrieve data from a MySQL database and store it in an array for comparison. My objective is to compare one variable ($row[0]) with another predefined variable, and based on the result, use the second variable ($row[1]) to perform a new query on ...

Is it possible for me to use ts files just like I use js files in the same manner?

So I recently stumbled upon TypeScript and found it intriguing, especially since I enjoy adding annotations in my code. The only downside is that I would have to change all my .js files to .ts files in order to fully utilize TypeScript's capabilities. ...

Interactive html5 canvas game with swiping mechanism

Currently, I am in the research phase for a new HTML5 canvas game that I want to create as a personal project to enhance my skills. Surprisingly, I have not been able to find any valuable articles or tutorials online about creating swipe-based games. The ...

What is the best way to search for a specific portion of a JSON key?

I am struggling to retrieve the JSON Key name because the complete name is not constant. I want to access the media_id_ value but the problem lies in the unpredictable numbers adjacent to it. My objective is to obtain the value of mediaFit, but I am faced ...

What is the best way to restrict event handling to only occur once every X seconds using jQuery or JavaScript?

Is there a way to limit handling the event of a rapidly-firing keypress to once per X seconds using jQuery or vanilla JavaScript? Check out this jsfiddle that demonstrates rapid keypress firing without any limiting on the handling: View here ...

Retrieve a single instance of every element within an array using JavaScript

I have an array of player objects, each containing properties such as "position" and "player_name". With 8 unique positions available for players, I aim to extract the first player for each position and transfer them to a new array. This way, the new array ...

Calculate the average value of the properties of a jQuery object

Consider the object below: rating { atmosphere: 85 cleanliness: 91 facilities: 91 staff: 85 security: 94 location: 78 valueForMoney: 85 } I'm looking to calculate the average of all these property values. Can y ...

Incorporating a hyperlink into an Iframe triggered by Fancybox2-AJAX, specific to the Iframe's unique identifier

One thing I have noticed is that everything seems to be working fine up until the point where I try to load it through fancybox via AJAX. An example of it working statically: <iframe id="videourl1" width="640" height="340" src="" frameBorder="0">& ...

Using Parseint in a Vue.js method

For instance, let's say this.last is 5 and this.current is 60. I want the sum of this.last + this.current to be 65, not 605. I attempted using parseInt(this.last + this.current) but it did not work as expected. <button class="plus" @click="plus"&g ...

JavaScript's toFixed method for decimals

I am encountering an issue with displaying prices for my products. I have labels in the form of "span" elements with prices such as 0.9, 1.23, and 9.0. I am using the method "toFixed(2)" to round these prices to two decimal places. However, I have notice ...

When the boolean in RxJS skipWhile remains true

My current scenario involves a specific use-case: There is a service that queues calculation tasks assigned with a certain ID. I have set up an observable to monitor the status of the service. When the ID is still in the queue, the query result is true (i ...

What is the best way to create a function that automatically resumes audio playback 3 seconds after the pause button is clicked?

I am looking to develop a basic webpage with an autoplay audio feature. The page would include a "pause" and "play" button. I aim to implement a function where clicking the "pause" button would stop the audio, but after 3 seconds, it would automatically re ...

Why is it that when declaring an array of objects, there is no need to use the new keyword inside the array initialization?

-------------------Unique Question:------------------------ In my coding adventure, I have crafted a Scene class and within it resides an array of scenes known as "scenes": class Scene { public: int id; string title; Image backgroundImage; ...

JavaScript - Returning an object using a promise

I'm facing an issue where I am struggling to retrieve an object with a specific structure, but I am unable to successfully return the object. When I inspect the code, I notice that if I log the data inside the promise, it shows the data. However, whe ...

The functionality of my JQuery validation plugin seems off when it comes to handling checkbox inputs

I created a versatile validation plugin that accepts a function to check input validity, along with callbacks for valid and invalid cases. The plugin consists of two functions: '$.fn.validation()' to attach validation logic and success/failure ca ...

Having trouble with sending information to the PHP server, unable to determine the root cause

Can someone help me figure out why the data from a form being sent to a php script for sending an email isn't working correctly? It's part of a template code but I suspect there might be an error. Specifically, I believe the {'userName' ...

In what way does React export a default function that invokes another function within the same file?

Within a JS file in React, I am exporting a default function to App.js. This exported function calls another function that was declared in the same file but was not explicitly exported. How does React know where to find this internal function? Does using e ...

Animating a gradient within an SVG element following along an SVG path

I successfully created an SVG egg and animated a path while adding a gradient, but I am facing an issue. The linear gradient goes from top to bottom, but I want the dark color at 0% and the light color at 100%. Essentially, I want the gradient to follow th ...

Attempting to conceal an element using a class in JavaScript, however, encountering a "unable to establish property 'class' of undefined" error

Whenever I click a button on my wordpress page, it triggers a function called "hideConstruction()" to hide all elements with the class ".construction". However, instead of achieving the intended result, I'm faced with the error message: "Cannot set p ...