1

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.

i.e 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]
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
Pravesh Khatri
  • 2,124
  • 16
  • 22
  • 2
    You need to post your code and explain what went wrong with it. Stack Overflow is not a "write my code" service, but we will help if you try and run into problems :) – Reinstate Monica Cellio May 31 '16 at 14:17
  • 2
    I agree with @Archer. Also, better replace 'hash' with 'hashmap' or similar - a 'hash' usually refers to the value resulting from hashing an object, not the datastructure. – le_m May 31 '16 at 14:19
  • Duplicate of [Getting JavaScript object key list](http://stackoverflow.com/q/3068534/218196) and [Sort array of objects by string property value in JavaScript](http://stackoverflow.com/q/1129216/218196). Try to divide the problem into sub-problems and find solutions for them. – Felix Kling May 31 '16 at 14:28

1 Answers1

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);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392