2

I have an array (myarray) which contains mixed case values ranging alphabets from a, A , ... z,Z. I am using the following mechanism to sort it irrespective of case that means all capital letters should come first as sorted and then the lowercase ones so that it looks like below after sorting :

Abc, Abd, abs, abp, Back, Bann, bike, ... and so on

I am doing it following way,

var myarray= new Array();
for (i=0; i<select.options.length; i++) {
myarray[i] = new Array();
myarray[i][0] = select.options[i].text;
myarray[i][1] = select.options[i].value;
}           


myarray.sort(function (a, b) {
    return a.toLowerCase().localeCompare(b.toLowerCase());
});

But I am getting the following error :

TypeError: a.toLowerCase is not a function

I am using the most commonly used function but still getting that above error and not finding any solution. Please help me with a better approach or point out what mistake I am making to get that error.

thanks.

4
  • 6
    What ​​​​is a? Commented Nov 30, 2014 at 16:59
  • 3
    toLowerCase is a method of String. Your array probably contains something else. Commented Nov 30, 2014 at 17:00
  • stackoverflow.com/questions/12611609/… Commented Nov 30, 2014 at 17:05
  • Yes , my array does not contain only strings. It is containing some <select> <option> values and text. The full code is posted in my answer, please see below Commented Nov 30, 2014 at 17:13

2 Answers 2

2

You're sorting array that consists of arrays, not strings, so you need to specify what item of array you want to use for sorting.

I don't know if you want to sort array by text or value, but lets assume you want to sort it by option value:

myarray.sort(function (a, b) {
    return a[1].toLowerCase().localeCompare(b[1].toLowerCase());
});
Sign up to request clarification or add additional context in comments.

Comments

0

So, really you have a nested arrays like

[ ['text1','valie1'],['text2','valie2'],['text2','valie2']]

but when you use your function

myarray.sort(function (a, b) {
    return a.toLowerCase().localeCompare(b.toLowerCase());
});

a and b is array like ['text1','valie1'], not the string

so you need change you sort function like

myarray.sort(function (a, b) {
    var textCompare = a[0].toLowerCase().localeCompare(b[0].toLowerCase());
    var valueCompare =a[1].toLowerCase().localeCompare(b[1].toLowerCase()); 
    return textCompare || valueCompare;
});

also in localeCompare function you can pass locale and options like sensitivity, so you don't need use toLowerCase

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.