var myArray = [ ['Bob',32], ['Mary',28], ['Alice',33], ... ];
I want to be able to resort this array (ascending/descending) by both name (myArray[i][0]) and age (myArray[i][1]). What's the easiest approach without creating a new array? Or is there one? I know of the sort() method, but wasn't sure that that would work here?
Thanks for responding guys. I'm trying to do a basic proof of concept and it's not working for me. I know i'm overlooking something simple, but i can't put my finger on it. Getting the generic error...
Code:
TypeError: Result of expression 'document.getElementById('message').innerHTML' [] is not a function.
Here's my markup...
Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Arrays</title>
<script type="text/javascript">
/* <![CDATA[ */
Array.prototype.sortMulti = function(){
var
argsLen = arguments.length,
args = arguments;
function custSort(a,b){
for(var i=0; i<argsLen; i++){
var
col = args[i],
x = a[col],
y = b[col];
if(x===y)continue;
return x > y;
}
return 0;
}
return this.sort(custSort);
}
var myArray = [
['fred',23],
['andy',34],
['sandra',48],
['sid',54],
['ian',15]
];
function printIt(){
document.getElementById('message').innerHTML(
myArray.sortMulti(0)
)
}
/* ]]> */
</script>
</head>
<body onload="printIt()">
<div id="message"></div>
</body>
</html>
Thanks Eric...i feel like a real idiot for not seeing that one. :P Now it's loading correctly, however the sortMulti() function doesn't seem to be having any affect on my array...
function printIt(){
var sorted = myArray.sortMulti(0);
var out = [];
for(var i=0;i<sorted.length;i++){
out.push(sorted[i].join("--"));
}
document.getElementById('message').innerHTML = out.join("<br/>");
}
Thanks for the updated code. It's working as you described it would in FireFox. For some reason it's not working in Safari. Is there a trick to make it more cross-browser?
Bookmarks