I have an array with following type of objects:
myArray = [
{state: "enabled", name: "zName"},
{state: "trying", name: "aName2"},
{state: "disabled", name: "aName3"},
{state: "disabled", name: "cName"},
{state: "disabled", name: "bName"}
]
I’m trying to sort the array in a way that it can be sort by:
state
==$givenValue
name
in ascending order of items that meet 1
As an example, if I wants to sort by state == "disabled"
, I’m expecting the array to sort as:
myArray = [
{state: "disabled", name: "aName3"},
{state: "disabled", name: "bName"},
{state: "disabled", name: "cName"},
{state: "trying", name: "aName2"},
{state: "enabled", name: "zName"}
]
Unfortunately, I’m having trouble to come-up with a solution by myself. Can you help (?)
4
Answers
To sort the array based on the given criteria (state == "disabled" and name in ascending order for items that meet the first criteria), you can use the Array.prototype.sort()
Yes, I can help you with that! You can use the Array.prototype.sort() method in JavaScript to sort the array based on the given criteria. Here’s an example of how you can achieve the desired sorting:
I would create an array to define the order ["enabled", "trying", "disabled"] and by the object value get the index from the array, so like you can sort them.