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

3
  • list.sort((a, b) => a.length - b.lenght)
    – rksh1997
    Apr 23, 2020 at 16:12
  • 2
    @RashadKokash, answers go down there. You short-circuit the process when you post them as comments.
    – isherwood
    Apr 23, 2020 at 16:13
  • 1
    because you are on the last index and you are trying to read the next index. There is no index after the last index Apr 23, 2020 at 16:13

1 Answer 1

0

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

list.sort((a, b) => a.length - b.length);
1

Not the answer you're looking for? Browse other questions tagged or ask your own question.