How can I use a string argument in JavaScript to sort an array of objects by that specific value?

Currently, I am implementing React and facing a challenge with creating a reusable sorting component. This component is meant to sort an array of objects based on a specific property field. For instance, imagine having an array of objects with properties as follows:

let seed = [
    {
        name: 'John', age: '35', cars : '4', income: '35000'
   },
   {
        name: 'Johnny', age: '15', cars : '0', income: '100'
   },
    {
        name: 'Mary', age: '45', cars : '41', income: '350000'
   },
]

To sort this array by the name property, you can do so using the following code snippet:

let sortedData = [...seed].sort((a, b) => (a.name > b.name ? 1 : -1));

My goal is to create a function that allows for dynamic sorting based on any given field, something like this:

function sortData(array, field) {
  array.sort((a, b) => (a.[field] > b.[field] ? 1 : -1))
}

However, it seems that the above syntax is not valid. Is there a way to achieve this without creating separate sorting functions for each individual property such as age, cars, income, etcetera?

Answer №1

Make sure to choose either bracket notation or dot notation for accessing keys in your code, but don't mix them together.

let seed = [
    {
        name: 'John', age: '35', cars : '4', income: '35000'
   },
   {
        name: 'Johnny', age: '15', cars : '0', income: '100'
   },
    {
        name: 'Mary', age: '45', cars : '41', income: '350000'
   },
]

function sortData(array, field) {
  return array.sort((a, b) => (a[field] > b[field] ? 1 : -1))
}

let sortedData = sortData([...seed], "cars");

console.log(sortedData);
.as-console-wrapper { max-height: 100% !important; top: auto; }

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

Removing entries in a Google spreadsheet by utilizing the API and executing a BatchUpdateRequest

Currently, I am working on sending a BatchUpdateRequest to the Google Sheets API in order to delete a row of data from a spreadsheet. Here is how my request is structured: var spreadsheetId = '1EV8S8AaAmxF3vP0F6RWxKIUlvF6uFEmsrOFWA1oNBYI'; ...

Prevent regex from matching leading and trailing white spaces when validating email addresses with JavaScript

In my current setup, I utilize the following regular expression for email validation: /^[a-zA-Z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$/ My attempt to validate the email is shown below: if (!event.target.value.match(/^[a-zA-Z0-9._%+-]+@[a-z0-9.-]+\. ...

invoke scrollToPosition function in React Native

I am trying to execute a function once the scrolling momentum is finished in my react native SectionList. After going through the documentation, I discovered onMomentumScrollEnd. However, the problem is that onMomentumScrollEnd only works when we manually ...

Take out the final elements from a numpy array

Here is a numpy array that I am working with: array([ 0.49010508, 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0.09438115, 0. , 0. , 0. , 0. , 0. , 0. , ...

Employing Jquery for restricting checkbox selection based on parent HTML elements

UPDATE I am looking to limit checkbox selection in specific sections on the same page. To prevent conflicting inputs from different sections, I believe using the label selector <label data-addon-name="xxx"> as a separator is the best appro ...

Is it possible to retract a message on Discord after it has been sent?

I have a code that automatically sends a welcome message when a new member joins the guild, and I want it to be deleted shortly afterwards. Here is my current code: client.on('guildMemberAdd', (member) => { var server = member.guild.id; i ...

Looking to expand the width of the sub menu to reach the full width of the

Is there a way to use CSS to make a sub-menu start from the left side of the screen instead of starting it below the parent item? nav { margin: 0 auto; text-align: center; } nav ul ul { display: none; } nav ul li:hover > ul { di ...

Toggle the sidebars to slide out and expand the content division using JavaScript

I am looking to achieve a smooth sliding out effect for my sidebars while expanding the width of the middle content div. I want this action to be toggled back to its original state with another click. Here's what I've attempted so far: $(' ...

Troubleshooting: Issue with Chrome's CSV Export Functionality in JavaScript/AngularJS

Currently, I am troubleshooting an issue with exporting a CSV file from a data table on a web application. The export functionality works fine on all browsers except for Chrome when the export button is clicked. I have been trying to solve this problem for ...

Angular - What causes variables to lose data after component changes?

Having an issue with two components - one creating and changing an array, and the other getting the array. The problem is that when retrieving the array in the second component, it only shows the default empty data. Code for array creation: export cla ...

What is the best approach for incorporating sub-navigation within a page popup in a Next.js project?

In the midst of my Next.js project, there is a requirement to showcase a chat popup consisting of multiple sub-pages like user registration, conversation page, and more. Hence, seamless navigation inside this popup is necessary. The idea is not to alter th ...

Angular version 8.2 combined with Firebase can result in errors such as those found in the `./src/app/app.module.ngfactory.js` file towards the end of the process when attempting to build with

My first time posing a query on this platform, and certainly not my last. The issue at hand involves the ng-build --prod process failing to complete and throwing errors in my Angular 8.2.14 application. I've integrated Firebase into my project succes ...

What could be causing the "keyframes method" in my css to not function correctly?

When working on the keyframes section, my computer seems to be having trouble recognizing the from part. Ideally, it should display in blue with the opacity command appearing in grey. Unfortunately, neither of these styles are appearing correctly and I&apo ...

What is the process of importing a JSON data file and utilizing it within a React component?

As a beginner in React, I am struggling with the concepts of importing, exporting, and rendering components. I have a fakeData.json file within the same src/components folder as the component I want to render. Let's take a look at the structure: < ...

Retrieving string-based JSON information

Within my text box, the user inputs strings separated by commas. These strings are split on the front end, then sent to the backend to retrieve data in JSON format. The interesting part is that when I directly entered the key of the JSON, like this, it wo ...

Desktop Safari displays Font-awesome icons with trimmed corners using a border-radius of 50%

While working on incorporating font awesome share icons into my project, I encountered an issue with getting a circle around them. After exploring various approaches, I opted for a CSS solution. Using React FontAwesome posed some challenges that led me to ...

Explore nearby directories by utilizing the HTML file API in conjunction with JavaScript

Exploring the idea of developing an application that utilizes the HTML5 file API and JavaScript to accept a directory path as user input, allowing for the processing (text search) of all files within that directory and its subdirectories. Instead of my cu ...

How can you include a comma between two objects within a string, excluding the last object, using JavaScript?

I have a string object stored in a variable passed from another class. My question is how can I add a comma between two objects, excluding the last object? Below is my code snippet: { "id":"57e4d12e53a5a", "body":"asdas", "publishe ...

Using JavaScript, adding an element to an array results in the array returning a value of 1

When I try to push a string into an array and then return the array, I am getting unexpected result of "1". Upon closer inspection, it seems that the array is being successfully created but before returning it, only "1" is being returned. Here is the snip ...

Sorting an array containing both integers and letters in Python

Sorting a list of integers and letters in a specific order can be a challenging task. Consider the following example: ex_array = [1, 3, 2', 2, 1', 3', 3] After sorting, the array should look like this: sorted(ex_array) = [1', 1, 2&ap ...