简体   繁体   中英

Javascript Sort a hash by values in array

I have a hash like below

 a ={ 
     0: [0, "A9"],
     2: [0, "A9.4"],           
     8: [0, "A9.1"],
     6: [1, "A9.5"],
     5: [0, "A9.2"],
     7: [2, "A9.3"]
 };

I need a sorted array corresponding to the second element of the array of every Value.

ie if my array is in the form of a = {key: [value_1_integer, value_2_string]}

I need to sort my hash by value_2_string so result array is

result = [0, 8, 5, 7, 2, 6]

You can apply Array#sort on the keys with a callback which takes the second elements of the property for sorting.

 var object = { 0: [0, "A9"], 2: [0, "A9.4"], 8: [0, "A9.1"], 6: [1, "A9.5"], 5: [0, "A9.2"], 7: [2, "A9.3"] }, keys = Object.keys(object).sort(function (a, b) { return object[a][1].localeCompare(object[b][1]); }); console.log(keys); 

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