简体   繁体   中英

How do I sort the keys in an array

I want to sort the stage key in ascending order. I want this order: {'stage_1','stage_2','stage_3','stage_11','stage_22'}

let data = {
    "stage_1": "PADIYANALLUR",
    "stage_11": "Weels India Rd.Jn.",
    "stage_2": "GUINDY TVK I.E",
    "stage_22": "RED HILLS",
    "stage_3": null,
}

Objects in JavaScript do not guarantee key ordering. You have to use arrays.

You can use Object.keys() and sort() to produce an ordered array of keys.

To order numerically based on the number suffix in your key, use +key.match(/\\d+/) to extract the digits and convert them to a number:

 const data = { "stage_1": "PADIYANALLUR", "stage_11": "Weels India Rd.Jn.", "stage_2": "GUINDY TVK IE", "stage_22": "RED HILLS", "stage_3": null, }; const result = Object.keys(data).sort((a, b) => +a.match(/\\d+/) - +b.match(/\\d+/)); console.log(result) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM