In JavaScript, click
constarray=
{
"A"—6,
"B"—1,
"C"—3
}
I would like to sort the array of objects such as in numerical order (higher order) by key.
What should I do?
constarray=
{
"A"—6,
"C"—3,
"B" : 1
}
Here's a very similar article:The question is not const but var, but it is equivalent.
Sorting JavaScript Object by property value
In the comment, the same content as @mok2pok's comment is attached to the comment, and it is highly evaluated.
The results of Google translation are as follows.
As for the question, the answer seems to be "I can't do it."
Before you read the answer: The answer is no.In ECMAScript, the order of object properties is not standard. Never assume the order of elements in a JavaScript object. An object is a collection of out-of-order properties. The answers below show how to "use" sorted properties with the help of an array, but do not actually change the order of properties for the object itself. So, no, that's impossible. Building objects using pre-sorted properties does not guarantee that they will appear in the same order in the future.
The above marked resolution pushes the defined object to another array variable and sorts it.
Similar Japanese content is at the end of the article below.
[JavaScript] Sort associative array keys by value
There are various types of answers to the article introduced by S.O., so you can replace it with the one you like.
Although the object properties are not sequential, the new Map
keys are guaranteed sequential.
However, the Map
does not have a standard mechanism to sort, so you must sort it yourself.
Dear Re:yoshi,
© 2024 OneMinuteCode. All rights reserved.