/    Sign up×
Bounties /Pin to ProfileBookmark

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

+ 1,000
Copy linkTweet thisAlerts:
Dec 06.2022

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
JavaScript

1 Replies

Copy linkTweet thisAlerts:
@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 GithubCreate Account
about: ({
version: 0.1.9 BETA 4.20,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...