Bounties /Pin to ProfileBookmark

How do you sort an array of JavaScript variables by one of its string property values?

Imagine we were building a to-do list application in JavaScript and you want to display the tasks in the order that they were added to the list. However, you also want to give the user the option to sort the tasks by priority level (low, medium, high). The priority level is stored as a string property in each task object in the array. In order to sort the tasks by priority level, we would need to sort the array of task objects by the string property value of the “priority” property.

to post a answer
December 6th, 2022JavaScript

1 Answer(s)

answer
@JaySODec 06, 2022 — To sort an array of objects in JavaScript in alphabetical order by city, you can use the Array.sort() method and provide a comparator function that compares the city properties of each object.

Here is an example:


var myObject = [
{ state: 'MA', city: 'Boston' },
{ state: 'RI', city: 'Providence' },
{ state: 'NH', city: 'Manchester' },
{ state: 'ME', city: 'Portland' },
{ state: 'MA', city: 'Amherst' }
];

myObject.sort(function(a, b) {
if (a.city b.city) {
return 1;
} else {
return 0;
}
});

// myObject is now sorted in alphabetical order by city


The Array.sort() method is called on the myObject array, and a comparator function is passed as an argument. This function compares the city properties of each object in the array, and returns a value indicating whether the object should be sorted before or after the other object in the array.

The Array.sort() method will then sort the array in place, so that the objects are now in alphabetical order by city. You can then access the sorted array using the myObject variable.
×

Success!

Help @hq spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with Github
about: ({
version: 0.1.7 BETA 2.4,
whats_new: article editor v2,
up_next: tip code demos,
coming_soon: embeddable tipping,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh

version: 0.1.5,
notes: added pins + new badge

version: 0.1.4,
notes: home refresh + tools
)...
recent_tips: (
tipper: @JohnDavis,
amount: 250 SATS,
source: article

tipper: @Megan0910,
amount: 1000 SATS,
source: article

tipper: @JohnDavis,
amount: 250 SATS,
source: article
)...