1

Trying to sort an array of strings by the number of letters of each array's value, I have this array:

 var list = ["rrr", "re", "r", "rrar"]

And the Output would be:

var list = ["r", "re", "rrr", "rrar"];

This is my code:

        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 don't understand why Chrome's Console gives me a "TypeError: list[(i + 1)] is undefined", I'm trying but I don't find where define that

isherwood
  • 58,414
  • 16
  • 114
  • 157
AlexisCP
  • 11
  • 2

1 Answers1

0

Don't reinvent the wheel: just use Array.prototype.sort.

list.sort((a, b) => a.length - b.length);
Aplet123
  • 33,825
  • 1
  • 29
  • 55
  • OK, now I see it's solved here: https://stackoverflow.com/questions/10630766/how-to-sort-an-array-based-on-the-length-of-each-element – AlexisCP Apr 24 '20 at 09:14