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]
3
  • 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 :) Commented May 31, 2016 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. Commented May 31, 2016 at 14:19
  • Duplicate of Getting JavaScript object key list and Sort array of objects by string property value in JavaScript. Try to divide the problem into sub-problems and find solutions for them. Commented May 31, 2016 at 14:28

1 Answer 1

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);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.