0

So I have this array:

[[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]], [3, "Half-Eaten Apple"],[7, "Toothpaste"]];

I want to sort the element of this array in alphabetic order accordingly to the second element. So I wanted to be ordered like this:

[[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [3, "Half-Eaten Apple"], [5, "Microphone"]], [7, "Toothpaste"]];

What can I do to accomplish this in javascript?

2
  • What did you try? Commented Jun 20, 2017 at 20:29
  • As @Nina points out, you have to decide who's locale (alphabet etc) you want to sort by: user's browser's, content's, server's, site's, site's organization's "headquarters's", …. Commented Jun 21, 2017 at 0:18

2 Answers 2

4

With a proper array and the use of the second item, you could use Array#sort with hint for Sorting non-ASCII characters for String#localeCompare for comparing strings.

var array = [[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"], [3, "Half-Eaten Apple"], [7, "Toothpaste"]];

array.sort(function (a, b) {
    return a[1].localeCompare(b[1]);
});

console.log(array);

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

2 Comments

Would you mind updating your reference to MDN? It is quite a bit more reliable than W3S
Thank you! You could also toss the #Sorting_non-ASCII_characters hash on the end of the Array#sort link to take it right to the localCompare example if you wanted
0
let stuff = [
  [21, "Bowling Ball"],
  [2, "Dirty Sock"],
  [1, "Hair Pin"],
  [5, "Microphone"],
  [3, "Half-Eaten Apple"],
  [7, "Toothpaste"]];

This can be accomplished easily by sorting the array items by using the String.prototype.localeCompare() method to put the items in alphabetical order.

stuff.sort((item1, item2) => item1[1].localeCompare(item2[1]));

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.