2017-04-04 36 views
5

示例輸入:排序範圍數組['55-66','> 55','<66']?

[ '50-59', '60-69', '40-49', '>=70', '<40' ] 

預期輸出

[ '<40', '40-49', '50-59', '60-69', '>=70' ] 

嘗試;擴大從我以前的單行(調試):

export function sort_ranges(ranges: string[]): string[] { 
    const collator = new Intl.Collator(undefined, { 
     numeric: true, 
     sensitivity: 'base', 
     ignorePunctuation: true 
    }); 
    return ranges.sort((a: string, b: string): number => { 
      const bNaN: boolean = !isNaN(parseInt(b[0])); 
      const col =() => 
       console.info(`collator(${a}, ${b}) = ${collator.compare(a, b)}` 
          ) || collator.compare(a, b); 
      if (a[0] === '<' && bNaN) { 
       console.info('< =', a); 
       return -1; 
      } 
      else if (a[0] === '>' || b[0] === '>') { 
       console.info('> =', a); 
       return 1; 
      } 
      else return col(); 
     } 
    ); 
} 

Runnable (mocha+chai in a plnkr)

注:範圍被保證是不重疊的,並且可能有其他的東西等「富」,其應該在陣列中在數組末尾以任何順序放置。

想法:我可以建立一個像[[50,59], ['<', '40']]這樣的新陣列,然後嘗試重寫.sort方法,但這似乎很瘋狂。有更好的解決方案嗎?

+3

我不知道爲什麼是'60-69'和''50-59'之前40-49'於預期的結果。 –

+0

哎呀,我的不好;複製它急於 –

+2

51-57會去哪裏? – mplungjan

回答

0

不幸的是,其他的答案沒有處理邊緣情形。作爲額外的獎勵,沒有正則表達式:

function sort_ranges(ranges/*: string[]*/)/*: string[]*/ { 
 
    return ranges.sort((a/*: string*/, b/*: string*/)/*: number*/ => { 
 
     if (a[0] === '<') return -1; 
 
     else if (a[0] === '>') return a[0].charCodeAt() - b[0].charCodeAt(); 
 
     else if (isNaN(parseInt(a[0])) || b[0] === '<') return 1; 
 
     else if (b[0] === '>' || isNaN(parseInt(b[0]))) return -1; 
 
     return parseInt(a.split('-')[0]) - parseInt(b.split('-')[0]) 
 
    }); 
 
} 
 

 
// Test code for StackOverflow: 
 

 
const expected_arrays = Object.freeze([ 
 
    [ '<40', '40-49', '50-59', '60-69', '>=70' ], 
 
    [ '40-49', '50-59', '60-69', '>=70', 'all' ] 
 
]); 
 

 
const input_arrays = Object.freeze([ 
 
    [ '60-69', '<40', '>=70', '50-59', '40-49' ], 
 
    [ '50-59', 'all', '40-49', '>=70', '60-69' ] 
 
]); 
 

 
for(let i=0; i<input_arrays.length; i++) 
 
    console.info(sort_ranges(input_arrays[i]), '===', expected_arrays[i]);

7

var a = [ '50-59', '60-69', '40-49', '>=70', '<40' ]; 
 

 
a.sort(function(a,b) { 
 
    if (a[0] === '<') return -1; 
 
    if (a[0] === '>') return 1; 
 
    if (b[0] === '<') return 1; 
 
    if (b[0] === '>') return -1; 
 
    return a.match(/\d+/)[0] - b.match(/\d+/)[0]; 
 
}); 
 

 
console.dir(a);

2

你可以匹配的數字,如果兩個號碼都可以,把它用於調整後的排序。

var array = ['50-59', '60-69', '40-49', '>=70', '<40', 'all']; 
 

 
array.sort(function (a, b) { 
 
    function getV(v) { return v.match(/\d+/g) || [Infinity, Infinity]; } 
 
    var aa = getV(a), 
 
     bb = getV(b); 
 

 
    return aa[0] - bb[0] || (aa[1] || aa[0]) - (bb[1] || bb[0]); 
 
}); 
 

 
console.log(array)

+0

如果您的'返回'中的任何元素爲空? –

+0

你可以添加一個默認值,比如'return(aa [0] || 0) - (bb [0] || 0)|| (aa [1] || aa [0] || 0) - (bb [1] || bb [0] || 0);' –

+0

'TypeError:bb爲null'。 PS:看到我的答案爲工作模型 –