簡體   English   中英

我需要如何對數字名稱 JS 進行排序。 而且我不能使用循環。 只有標准的數組方法

[英]How I need to Sorts digit names JS. And I cant use loops. Only standard Array methods

例子:

 *   [] => []
 *   [ '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' ]
 */

我想你甚至不知道如何開始,這就是你甚至沒有嘗試的原因。

無論如何,這是一種方法,它是如何完成的:

 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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM