Hello everyone,
I'm trying to sort a two-dimensional array by it's second[1] and third[2] position.
I managed to sort it by it's first[0] position with the simple sort() function, but I can't seem to find any working solution to what I want.
I've added my code and the final output I'm trying to achieve:
printArr() and sortByName() works great! I need help with the sortByPhone() and sortByEmail() ones.
<script type="text/javascript">
var studentArr = new Array();
studentArr[0] = new Array("Lior Iluz", "03-7262123", "lior@domain.com");
studentArr[1] = new Array("David Abutbul", "08-5232424", "david@domain.com");
studentArr[2] = new Array("Lior Bourla", "04-6232424", "lior@domain.com");
studentArr[3] = new Array("Adi Efrati", "08-9232427", "adi@domain.com");
studentArr[4] = new Array("Yossi Morad", "04-4232427", "yossi@domain.com");
studentArr[5] = new Array("Avishai Davis", "03-6232427", "avishai@domain.com");
studentArr[5] = new Array("Petra Russo", "04-7232427", "petra@domain.com");
function printArr(){
document.getElementById('table').innerHTML = '<h2>Students List</h2';
document.getElementById('table').innerHTML += '<p><span class="col1"><font color="#265e16"><strong>#</strong></font></span></span><span class="col2"><a href="index.html" title="Sort By Name" onclick="sortByName();return false;">Name</a></span><span class="col3"><a href="#" onlick="sortByPhone();return false;">Phone</a></span><span class="col4"><a href="#" onlick="sortByEmail();return false;">Email</a></span></p><div class="cleaner"></div>';
for (var i = 0; i < studentArr.length; i++) {
document.getElementById('table').innerHTML += '<p><span class="col1">' + i + '</span><span class="col2">' + studentArr[i][0] + '</span><span class="col3">' + studentArr[i][1] + '</span><span class="col4">' + studentArr[i][2] + '</span></p><div class="cleaner"></div>';
}
}
//a working simple sort - sorts by the first[0] position
function sortByName(){
studentArr.sort();
printArr();
}
//a tryout with a script I've found while searching all over google ;)
function numberSort(a,b){
return ((a[1] < b[1]) ? -1 : ((a[1] > b[1]) ? 1 : 0));
}
function sortByPhone(){
studentArr.sort(numberSort());
printArr();
}
//same as sortByPhone() but I thought maybe it'll work on this one :\
function sortByEmail(){
studentArr.sort(numberSort());
printArr();
}
</script>
the output I want is:
sortByPhone();
03-7262123
04-4232427
04-6232424
04-7232427
08-5232424
08-9232427
and:
sortByEmail(); - //I know when I use sortByName it also sort the emails but that's only because I used emails with the same names as the user name itself... (fake emails...)
[email]adi@domain.com[/email]
[email]david@domain.com[/email]
[email]lior@domain.com[/email]
[email]lior@domain.com[/email]
[email]petra@domain.com[/email]
[email]yossi@domain.com[/email]
Thank you very much!