0

It convenient to sort elements by arbitrary letter as:

 In [3]: a.sort(key=lambda e:e[1])                                         $

 In [4]: a                                                                 $
 Out[4]: ['second', 'element', 'sort', 'by']

Is it possible to get it done with js?

[ 'test', 'array', 'sort' ]
> a.sort((a, b) => a[1] - b[1])
[ 'test', 'array', 'sort' ]
> a.sort((a, b) => a[2] - b[2])
[ 'test', 'array', 'sort' ]
AbstProcDo
  • 19,953
  • 19
  • 81
  • 138
  • 5
    are you after something like `arr.sort((a, b) => a[1].localeCompare(b[1]));` ? – Nick Parsons Jan 08 '21 at 03:59
  • 1
    Probably a duplicate of [*Sort array of objects by string property value*](https://stackoverflow.com/questions/1129216/sort-array-of-objects-by-string-property-value) from 11 years ago. 3,000 votes, 57 answers. Probably one of those will do. – RobG Jan 08 '21 at 04:03

2 Answers2

2

maybe there is an easy way, this is what I have

console.log(['element', 'by', 'sort', 'second'].sort((a,b) => {
  a1 = a.substring(1,2);
  b1 = b.substring(1,2);
  if (a1 === b1) {
    return 0;
  }
  return a1 > b1 ? 1 : -1;
}));
D. Seah
  • 4,472
  • 1
  • 12
  • 20
1
['test','array','sort'].sort((a,b) => a.charCodeAt(1)-b.charCodeAt(1));
Matt Miguel
  • 1,325
  • 3
  • 6