-4

ok, this might have an answer but I'm not sure how to word it to find it. I have a list of lists.

var listOLists = [['q','w','e'],['a'],['z','x']];

is there a way to sort it by length of lists, so I get a result

output.table(listOLists.specialLenghtsort());
    'a'
    'z','x'
    'q','w','e'
user1869582
  • 449
  • 1
  • 3
  • 10

1 Answers1

1

Yes, you can use array sort method with a custom compare function.

listOLists.sort((a, b) => a.length > b.length ? 1 : -1)

If you want the order of same length item to be preserved you need to do the following,

listOLists.sort((a, b) => a.length - b.length)

Thanks to Patrick for pointing that out. For reference you can follow this this link.

Md Sabbir Alam
  • 4,937
  • 3
  • 15
  • 30
  • 1
    That's not a stable algorithm. That will likely swap any elements with equal lengths rather than preserving their initial relative ordering. – Patrick Roberts Oct 27 '20 at 05:09
  • I have tried that, it is actually preserving relative ordering for an equal length. – Md Sabbir Alam Oct 27 '20 at 05:11
  • [Are you sure about that?](https://i.stack.imgur.com/sTXwk.png) – Patrick Roberts Oct 27 '20 at 05:15
  • @Patrick True, but the question doesn't seem to require a stable algorithm. – Brian McCutchon Oct 27 '20 at 05:16
  • In Firefox it is actually preserving the order. But after I in chrome, it breaks the order. Interesting. Thanks @PatrickRoberts for pointing that out. – Md Sabbir Alam Oct 27 '20 at 05:20
  • @BrianMcCutchon actually it is. Starting in ECMAScript 2019, the builtin `sort()` method is required by the specification to implement a stable sort algorithm (since before 2019, most engines already did except V8, which only [adopted a stable algorithm in 2018](https://v8.dev/blog/array-sort)). So yes, as long as the callback returns `0` for two comparatively equal elements, the specification requires the builtin method to preserve their relative ordering as of 2019. – Patrick Roberts Oct 27 '20 at 05:23
  • @BrianMcCutchon read the paragraph about ECMAScript 2019 in the [introduction section](https://www.ecma-international.org/ecma-262/#sec-intro). – Patrick Roberts Oct 27 '20 at 05:25
  • @BrianMcCutchon and also [this](https://stackoverflow.com/a/3027715/1541563) – Patrick Roberts Oct 27 '20 at 05:32