Get an array of objects sorted based on numerical values, ignoring strings

After developing a utility function to sort an array of objects based on either ascending or descending order, I encountered an issue when sorting string properties. For example, if "age" is passed as the second argument, the ordering works correctly. However, when "job" is passed, nothing happens. The expected behavior was for it to alphabetically order by job titles (Engineer, Marketing, Sales). Any suggestions on how to resolve this issue or why it is happening?

const arrayOfObjects = [
  { firstName: 'Joe', job: 'Engineer', age: 22 },
  { firstName: 'Sam', job: 'Sales', age: 30 },
  { firstName: 'Claire', job: 'Engineer', age: 40 },
  { firstName: 'John', job: 'Marketing', age: 29 },
  { firstName: 'Susan', job: 'Engineer', age: 21 },
];

const orderByValue = (array, orderByItem, order) => array.sort((a, b) => {
  if (order === 'descending') {
    return b[orderByItem] - a[orderByItem];
  } else {
    return a[orderByItem] - b[orderByItem];
  }
});

// console.log('order by age:', orderByValue(arrayOfObjects, 'age'));
console.log('order by job:', orderByValue(arrayOfObjects, 'job'));

Answer №1

Utilize the LocaleCompare method with the Numeric option to effectively handle numbers in JavaScript.

Since LocaleCompare is a String method, make sure to convert Number types correctly by using .toString(), a[orderByItem] + '', or String(a[orderByItem]).

const arrayOfObjects = [
  { firstName: 'Joe', job: 'Engineer', age: 22 },
  { firstName: 'Sam', job: 'Sales', age: 30 },
  { firstName: 'Claire', job: 'Engineer', age: 40 },
  { firstName: 'John', job: 'Marketing', age: 29 },
  { firstName: 'Susan', job: 'Engineer', age: 21 },
];

const orderByProperty = (array, orderByItem, order) => array.sort((a, b) => {
  if (order === 'descending') {
    return b[orderByItem].toString().localeCompare(a[orderByItem].toString(), 'en', {numeric: true});
  } else {
    return a[orderByItem].toString().localeCompare(b[orderByItem].toString(), 'en', {numeric: true});
  }
});

console.log('order by age:', orderByProperty(arrayOfObjects, 'age'));
console.log('order by job:', orderByProperty(arrayOfObjects, 'job'));
.as-console-wrapper {max-height: 100% !important; top: 0;}

Answer №2

You can simplify the comparison process by returning a function as a callback.

This method utilizes greater/smaller operators for comparisons, which also work efficiently with strings.

const arrayOfObjects = [
  { firstName: 'Joe', job: 'Engineer', age: 22 },
  { firstName: 'Sam', job: 'Sales', age: 30 },
  { firstName: 'Claire', job: 'Engineer', age: 40 },
  { firstName: 'John', job: 'Marketing', age: 29 },
  { firstName: 'Susan', job: 'Engineer', age: 21 },
];

const orderByProperty = (array, orderByItem, order) => array.sort(order === 'descending'
    ? (a, b) => b[orderByItem] > a[orderByItem] || -(b[orderByItem] < a[orderByItem])
    : (a, b) => a[orderByItem] > b[orderByItem] || -(a[orderByItem] < b[orderByItem])
);

console.log('order by age:', orderByProperty(arrayOfObjects, 'age'));
console.log('order by job:', orderByProperty(arrayOfObjects, 'job'));
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

Spinning a 3-dimensional vector in THREE.js using dual axes

Apologies for potentially posting a duplicate question. I am working with two 3D vectors: Center: (0, 0, 0) Orb: (0, 0, 100) My goal is to rotate the orb-vector around the center-vector on both the X and Y axes to ensure an object is always in view of ...

JQuery Slideshow Automation

I have created a slideshow using Javascript and JQuery for my webpage. However, I am encountering an issue where only one of the slideshows cycles through all the pictures and then starts over, while the second one ends after cycling once. Can someone as ...

Unintroduced jQuery Keyup

I am currently working on a project where I am trying to incorporate an autocomplete feature into an input form. My approach involves using jQuery to trigger an AJAX call to a servlet and adding a listener on the input field for keyup events. However, it s ...

Customizing Marker Clusters with ui-leaflet: A guide on changing marker cluster colors

I'm trying to customize the markerCluster color in a non-default way. I've been exploring the API and it looks like the recommendation is to modify a divIcon after creation, possibly like this: var markers = L.markerClusterGroup({ iconCreateFunc ...

Refrain from using inline JavaScript code within your

Here is the basic structure of my code: <a href="javascript:void(0);" onClick="viewServices(1)">Services</a> <a href="javascript:void(0);" onClick="viewServices(43)">Services</a> <a href="javascript:void(0);" onClick="viewServic ...

Error: The function 'enter' cannot be called on the data selection from the SVG append and attribute select statement in the code

I am attempting to replicate the force-directed graph showcased by Bostock in this example https://bl.ocks.org/mbostock/4062045 using my own dataset. By leveraging Django serializers to parse the JSON-formatted data, I have successfully retrieved the requ ...

How to Retrieve a Specific Line with jQuery

Could jQuery be used to retrieve the offset of the first letter in the 5th visual line of a block's content? I am referring to the visual line determined by the browser, not the line seen in the source code. ...

The pagination feature of the material-ui data grid is experiencing issues with double clicks because of its compatibility with the react-grid-layout library for

I am currently using the react-grid-layout library to manage the resizing of both charts and a material-ui data grid table. However, I am encountering an issue where when clicking on the table pagination arrow, it does not work properly. I have to click tw ...

Access our iOS app to seamlessly open our website in your browser. Clicking on a link within our website will

How can we achieve the objective of having a button in an iOS native app that, when clicked, opens a URL (webpage) in a native browser like Safari, and then uses JavaScript in the opened webpage to close that browser window and reveal the app again? While ...

Designing object schema for MongoDB metadata

Please forgive my lack of knowledge in computer terminology: In my Mongo app, I aim to establish a defined structure for each document type. This structure will include constraints, validation patterns, and access roles for viewing, modifying, and deletin ...

When the file is active on a local machine, the bot commands run smoothly. However, these commands do not execute on a remote

Lately, while working on coding a discord bot using discord.js, I came across an issue. Whenever I run my bot on my local machine, all the commands work perfectly fine. However, after committing and pushing the code to GitHub, and then allowing buddy.works ...

Is there a method similar to insertBefore that works with arrays and/or HTMLCollections?

Is there a vanilla JavaScript or jQuery function that works like Node.insertBefore(), but for arrays and/or HTMLCollections? An example of what I'm looking for: var list = document.getElementsByClassName("stuff"); var nodeToMove = list[0]; var other ...

Does the user need to download the scripts from Google API multiple times during the insertion process?

Concerned about the potential need for multiple downloads of a script from an unknown location on the user's computer, I would like to explore options to mitigate this issue. Specifically, I am considering creating a condition to check the download st ...

The Material UI button shifts to a different row

I need help adjusting the spacing between text and a button on my webpage. Currently, they are too close to each other with no space in between. How can I add some space without causing the button to move to the next line? const useStyles = makeStyles((the ...

Tips for retrieving values from numerous checkboxes sharing the same class using jQuery

Currently, I am struggling with getting the values of all checkboxes that are checked using jquery. My goal is to store these values in an array, but I am encountering difficulties. Can anyone provide me with guidance on how to achieve this? Below is what ...

Navigate array in vue-chart.js

I've been utilizing Vue-chartjs with Laravel 5.7 for my project. The goal: I aim to pass an array to Vue so that I can dynamically generate a chart by looping through specific values. My approach so far: Here's the array I'm working with ...

Choose from the options provided to display the table on the screen

One of the challenges I am facing involves a table with two columns and a select option dropdown box. Each row in the table is associated with a color - green indicates good, red indicates bad, and so on. My goal is to have all values displayed when the pa ...

[ERROR_HTTP_HEADERS_ALREADY_SENT]: Headers can't be set once they have been sent to the client, expressjs

Whenever I attempt to insert data into my MySQL database using the express router function, I encounter an error. It appears that my server is trying to send a response twice, but I am unsure of where the issue lies. Here is the error message: throw err; / ...

What are the steps to modify the authorization header of an HTTP GET request sent from a hyperlink <a href> element?

I have a unique Angular application that securely saves JWT tokens in localstorage for authentication purposes. Now, I am eager to explore how to extract this JWT token and embed it into an HTTP GET request that opens up as a fresh web page instead of disp ...

Custom variables can be passed to subscription buttons through Paypal

I am currently working on finding a solution to passing custom variables when applying for a subscription for my created web service. The code on the front end that I have implemented so far is as follows: const createSubscription = (data, actions) => { ...