我需要如何对数字名称进行排序 JS。而且我不能使用循环。仅标准数组方法

问题描述 投票:0回答:2

示例:

 *   [] => []
 *   [ 'nine','one' ]                 => [ 'one', 'nine' ]
 *   [ 'one','two','three' ]          => [ 'one','two', 'three' ]
 *   [ 'nine','eight','nine','eight'] => [ 'eight','eight','nine','nine']
 *   [ 'one','one','one','zero' ]     => [ 'zero','one','one','one' ]
 */
javascript sorting
2个回答
0
投票

我想你甚至不知道如何开始,所以你甚至没有尝试过。

无论如何,这是一种方法,如何做到:

const input = ['nine','eight','nine','eight', 'one','two','three']

const digitsComparator = (a, b) => {
  const mapper = ['zero', 'one', 'two', 'three', 'four',
                  'five', 'six', 'seven', 'eight', 'nine']
  return mapper.indexOf(a) - mapper.indexOf(b) 
}

const res = input.sort(digitsComparator)

console.log(res)


0
投票
arr = [ 'nine','eight','nine','eight'];

const mapper = ['zero', 'one', 'two', 'three', 'four',
    'five', 'six', 'seven', 'eight', 'nine'];

return arr.sort((a, b) => mapper.indexOf(a) - mapper.indexOf(b))
© www.soinside.com 2019 - 2024. All rights reserved.