Reputation: 4061
I'm learning javascript and can't figure out the problem in my code below. I guess I misunderstand how arrays actually work.
The problem is that the alerted array is not actually sorted. I would be grateful for any insights on this:
HTML:
<html>
<head>
<title>
Test 1
</title>
<script src="http://code.jquery.com/jquery-latest.js" type=
"text/javascript">
</script>
</head>
<body>
<div class="items">
<ul>
<li>
<a href="#" id="1">Link 1</a>
</li>
<li>
<a href="#" id="2">Link 2</a>
</li>
<li>
<a href="#" id="3">Link 3</a>
</li>
<li>
<a href="#" id="4">Link 4</a>
</li>
</ul>
</div>
</body>
</html>
Javascript:
var clickedLinks = [];
var passedItems = [];
// Collect clicked link IDs into an array and pass the array as an argument to shoplist()
$('.items a').click(function () {
if (clickedLinks.indexOf(this.id) != -1) {
var linkIndex = clickedLinks.indexOf(this.id);
clickedLinks.splice(linkIndex, 1);
} else {
clickedLinks.push(this.id);
}
shoplist(clickedLinks);
});
function shoplist(ids) {
passedItems.push(ids.slice());
alert(passedItems.sort());
}
Steps to reproduce:
Expected Result: 1, 2, 2
Actual Result: 2, 2, 1
Things I've tried:
function shoplist(ids) {
passedItems.push(ids.slice());
var newpi = passedItems.slice();
alert(newpi.sort());
}
Upvotes: 1
Views: 90
Reputation: 91309
You are adding an array, the result of ids.slice()
, to another array. That's why the sort doesn't work as you expect. Use concat
instead, if you want to add the contents of ids
to the passedItems
array:
passedItems = passedItems.concat(ids);
Also, instead of adding a string to the ids
array, you should use .push(parseInt(this.id))
instead, and then use:
passedItems.sort(function (a, b) {
return a - b;
});
Upvotes: 1
Reputation: 11714
I think you're using the sort function wrong. If you want to use the sort function numerically, you have to include a sort function. If you want to sort things numerically you should use this function (provided in the link):
(function(a,b){return a-b});
So in your scenario for the newpi it would look like this:
newpi.sort(function(a,b){return a-b});
Upvotes: 2