-3

This is the JavaScript code to alphabetically sort the array, however i was searching for a way to bubble sort each item one at a time using a loop. please can you suggest a way of doing this or another alternative to sort()

var products = ["Printer", "Tablet", "Router", "Scanner", "Moniter", "Projector", "USB", "Keyboard"]
document.getElementById("alphabetical.order").innerHTML = products;
function alphabetical() {
    products.rsort();
    document.getElementById("alphabetical.order").innerHTML = products;
} 
s1234
  • 1
  • 5
  • 3
    What is wrong with `sort`? – Quentin Jan 22 '17 at 14:39
  • I was wondering if there was any other ways of doing it – s1234 Jan 22 '17 at 14:40
  • 1
    There are, but the ones that spring to mind are massively impractical. Use `sort` that's what it is there for. – Quentin Jan 22 '17 at 14:42
  • 2
    if you're interested in how to sort on your own, you can take a look at this page: it shows an animation of how the sorting algorithms work and show pseudocode with it: https://visualgo.net/sorting – Thomas Altmann Jan 22 '17 at 14:42
  • thank you, this was really helpful to learn how to sort integers with a loop however how could i use that to implement the use of string? – s1234 Jan 22 '17 at 14:48
  • well, if the pseudocode says something like `if leftElement > rightElement` you do the same with strings: http://stackoverflow.com/questions/2167602/optimum-way-to-compare-strings-in-javascript – Thomas Altmann Jan 22 '17 at 15:07
  • would it make sense to assign values to the strings? – s1234 Jan 23 '17 at 17:47

1 Answers1

1
products.sort(function(a, b) {  
    return a.toLowerCase() > b.toLowerCase() ? 1 : -1;
});
xlm
  • 6,854
  • 14
  • 53
  • 55
yumna
  • 11
  • 2