TypeScript sorting an array

匿名 (未验证) 提交于 2019-12-03 02:45:02

问题:

I've been trying to figure out a very strange issue I ran into with typescript. It was treating an inline Boolean expression as whatever the first value's type was instead of the complete expression.

So if you try something simple like the following:

var numericArray:Array<number> = [2,3,4,1,5,8,11];  var sorrtedArray:Array<number> = numericArray.sort((n1,n2)=> n1 > n2); 

TryIt

You will get an error on your sort method saying the parameters do not match any signature of the call target, because your result is numeric and not Boolean. I guess I'm missing something though cause I'm pretty sure n1>n2 is a Boolean statement.

回答1:

The error is completely correct.

As it's trying to tell you, .sort() takes a function that returns number, not boolean.

You need to return negative if the first item is smaller; positive if it it's larger, or zero if they're equal.



回答2:

When sorting numbers, you can use the compact comparison:

var numericArray: number[] = [2, 3, 4, 1, 5, 8, 11];  var sortedArray: number[] = numericArray.sort((n1,n2) => n1 - n2); 

i.e. - rather than <.

If you are comparing anything else, you'll need to convert the comparison into a number.

var stringArray: string[] = ['AB', 'Z', 'A', 'AC'];  var sortedArray: string[] = stringArray.sort((n1,n2) => {     if (n1 > n2) {         return 1;     }      if (n1 < n2) {         return -1;     }      return 0; }); 


回答3:

Great answer Sohnee. Would like to add that if you have an array of objects and you wish to sort by key then its almost the same, this is an example of one that can sort by both date(number) or title(string):

    if (sortBy === 'date') {         return n1.date - n2.date     } else {         if (n1.title > n2.title) {            return 1;         }         if (n1.title < n2.title) {             return -1;         }         return 0;     } 

Could also make the values inside as variables n1[field] vs n2[field] if its more dynamic, just keep the diff between strings and numbers.



回答4:

var numericArray: number[] = [2, 3, 4, 1, 5, 8, 11];  var sortFn = (n1 , n2) => number { return n1 - n2; }  var sortedArray: number[] = numericArray.sort(sortFn); 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!