Having trouble sorting an array of strings based on the length of each string? Take a look at this example:
var list = ["rrr", "re", "r", "rrar"]
The sorted output should be:
var list = ["r", "re", "rrr", "rrar"];
Below is the code I've been working with:
var list = ["rrr", "re", "r", "rrar"];
n = 4;
x = -1;
document.write(" list before: " + list);
for (k = 0; k < n; k++) {
list[x] = list;
for (i = 0; i < n-k; i++) {
if (list[i + 1].length < list[i].length) {
aux = list[i];
list[i] = list[i + 1];
list[i + 1] = aux;
}
}
}
document.write(" list after: " + list);
I'm encountering a "TypeError: list[(i + 1)] is undefined" in Chrome's Console. I have been trying to debug it, but I can't seem to pinpoint where the issue lies. Any suggestions?