0

I am using jquery to extract text of a set of elements into an array and want to sort them after inserting an element into the array. However, the sort is not working (as in the array remains in the same order after the sort). What's wrong? Code excerpt is below:

var sortedList = [];
$("div.resource").each(function(i, item) {
    var resource = $(this).html().toLowerCase();
    sortedList.push(resource);
})

// Add the new item 
sortedList.push(resource_name.toLowerCase());

alert("before sort");
for (var i = 0; i < sortedList.length; i++) {
    alert(sortedList[i]);
}

// Sort the list
sorted = sortedList.sort();

alert("after sort");
for (var i = 0; i < sorted.length; i++) {
    alert(sorted[i]);
}
8
  • 3
    Please, create an example with some array itens... Commented Jul 23, 2012 at 20:24
  • Instead of alerting in a loop, you can just console.log the array... (console.log(sorted);) Commented Jul 23, 2012 at 20:26
  • 3
    Works for me: jsfiddle.net/rxRFm Commented Jul 23, 2012 at 20:26
  • @davidbuzatto I am not sure I understand your comment. I already tested that sort works fine when it is given a hardcoded array of strings like so: var array = ["test", "fry", "aba"];. Commented Jul 23, 2012 at 20:26
  • 4
    You're using .html() so you might be getting HTML tags in there (if the elements have children). Try using .text() instead. Also, try to $.trim() the strings. Commented Jul 23, 2012 at 20:27

2 Answers 2

2

You should try this:

var sortedList = [];
$("div.resource").each(function(i, item) {
    var resource = $.trim($(this).text()).toLowerCase();
    sortedList.push(resource);
})
Sign up to request clarification or add additional context in comments.

Comments

2

In addition to the suggestions to use text() instead of html() and to trim the strings, wrap everything in the jQuery Document Ready function which will give the elements and jQuery library time to load (if you haven't already done that).

Beyond that it could be a browser issue. It works for me in chrome using both html() and text(). Though I made sure the elements only have text in them.

Also probably not a huge issue but your .each() method is missing a semi-colon.

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.