0

Assume I have this arrray: ['a', 'c', 'bb', 'aaa', 'bbb', 'aa']. I want to sort it in this way:

aaa, aa, a, bbb, bb, c.

this.array= this.array.sort((n1, n2) => n1.localeCompare(n2));
this.array= this.array.sort((n1, n2) => n2.length - n1.length);

But this is not right. How can I fix it?

reymon359
  • 1,240
  • 2
  • 11
  • 34
travis_91
  • 171
  • 2
  • 13
  • 2
    After first sort, add another sort by length? `.sort((a,b) => b.length - a.length);` :) – halilcakar Jun 30 '20 at 07:53
  • Does this answer your question? [Javascript sort function. Sort by First then by Second](https://stackoverflow.com/questions/9175268/javascript-sort-function-sort-by-first-then-by-second) – Liam Jun 30 '20 at 07:55
  • 1
    @HalilÇakar that will just sort the array by length of each string. – adiga Jun 30 '20 at 07:58
  • `sort` mutates the array. So, there is no need to reassign: `this.array = this.array.sort(...)` – adiga Jun 30 '20 at 08:00
  • @adiga right yea i really didn't think of it – halilcakar Jun 30 '20 at 08:00

1 Answers1

2

You could check if one string starts with the other and take the delta of the length as return value.

var array = ['a', 'c', 'bb', 'aaa', 'bbb', 'aa'];

array.sort((a, b) => {
    let d = a.startsWith(b) || b.startsWith(a)
            ? b.length - a.length
            : 0;

    return d || a.localeCompare(b);
});

console.log(array);

Without String#startsWith:

var array = ['a', 'c', 'bb', 'aaa', 'bbb', 'aa'];

array.sort((a, b) => {
    let min = Math.min(a.length, b.length),
        d = a.slice(0, min) === b.slice(0, min)
            ? b.length - a.length
            : 0;

    return d || a.localeCompare(b);
});

console.log(array);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • I don't know by default if in my array I have characters 'a' or 'b'. It's just an example.. it's a dynamic array – travis_91 Jun 30 '20 at 08:00
  • just try with you dynamic content. – Nina Scholz Jun 30 '20 at 08:01
  • strange.. it says me a.startsWith is not a function. I also explicit a:string, b:string – travis_91 Jun 30 '20 at 08:10
  • @travis_91 you could use square bracket notation `arr.sort((a, b) => a[0] == b[0] ? b.length - a.length : a.localeCompare(b))` – Yousaf Jun 30 '20 at 08:12
  • you could take a [polyfill](https://github.com/mathiasbynens/String.prototype.startsWith) for [`String#startsWith`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith) – Nina Scholz Jun 30 '20 at 08:14
  • no I did a wrong thing.. fixed. It's work like a charm!! thank you very much – travis_91 Jun 30 '20 at 08:17