0

I have an array of strings: [ 'a', 'aa', 'aaa' ]. If I compare those using the sort() method, I am getting something like this: ['aaa', 'aa', 'a'] but what I want is to compare them based on the characters and index 0 only so the input above will not change when I apply the sort() method. I know the reason why I am getting this ['aaa', 'aa', 'a'] but I need to compare them only based on the chars at 0s.

Please someone let me know.

Afzal18
  • 19
  • 4
  • You can pass a callback to `.sort()` to write your own sorting logic, [here's](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) the docs for more info. – Nick Parsons Oct 22 '22 at 06:48
  • Yes, I tried this. array.sort((a, b) =>a[0] - b[0] ) but it did not work somehow. a[0] should choose the first char of the string at pos 0, right? – Afzal18 Oct 22 '22 at 06:52
  • 1
    With `a[0] - b[0]` you're trying to subtract `'a'` from `'a'` (ie: `'a' - 'a'`), which will give you `NaN`. You can usee something like `localeCompare()` instead: `(a, b) =>a[0].localeCompare(b[0])` (also, please always add your attempt to your question) – Nick Parsons Oct 22 '22 at 06:55

1 Answers1

0

As @Nick Parsons already mentioned in his comment:

const arr=["aaa","b","aa","a","bb"];

console.log(arr.sort((a,b)=>a[0].localeCompare(b[0])))
Carsten Massmann
  • 26,510
  • 2
  • 22
  • 43