TypeScript 对数组进行排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21687907/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 01:11:51  来源:igfitidea点击:

TypeScript sorting an array

typescript

提问by Kent Cooper

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.

您将在 sort 方法中收到错误消息,指出参数与调用目标的任何签名都不匹配,因为您的结果是数字而不是布尔值。我想我遗漏了一些东西,因为我很确定 n1>n2 是一个布尔语句。

回答by Fenton

Numbers

数字

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 <.

-而不是<

Other Types

其他类型

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;
});

Objects

对象

For objects, you can sort based on a property, bear in mind the above information about being able to short-hand number types. The below example works irrespective of the type.

对于对象,您可以根据属性进行排序,请记住上述有关能够简写数字类型的信息。无论类型如何,以下示例都有效。

var objectArray: { age: number; }[] = [{ age: 10}, { age: 1 }, {age: 5}];

var sortedArray: { age: number; }[] = objectArray.sort((n1,n2) => {
    if (n1.age > n2.age) {
        return 1;
    }

    if (n1.age < n2.age) {
        return -1;
    }

    return 0;
});

回答by SLaks

The error is completely correct.

错误是完全正确的。

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

正如它试图告诉你的那样,.sort()需要一个返回数字而不是布尔值的函数。

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

如果第一项较小,则需要返回负数;如果较大则为正,如果相等则为零。

回答by yairniz

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.

也可以将里面的值作为变量 n1[field] vs n2[field] 如果它更动态,只需保持字符串和数字之间的差异。

回答by Yoav Schniederman

let numericArray: number[] = [2, 3, 4, 1, 5, 8, 11];

let sortFn = (n1 , n2) => number { return n1 - n2; }

const sortedArray: number[] = numericArray.sort(sortFn);

Sort by some field:

按某个字段排序:

let arr:{key:number}[] = [{key : 2}, {key : 3}, {key : 4}, {key : 1}, {key : 5}, {key : 8}, {key : 11}];

let sortFn2 = (obj1 , obj2) => {key:number} { return obj1.key - obj2.key; }

const sortedArray2:{key:number}[] = arr.sort(sortFn2);

回答by WasiF

Sort Mixed Array (alphabets and numbers)

排序混合数组(字母和数字)

function naturalCompare(a, b) {
   var ax = [], bx = [];

   a.replace(/(\d+)|(\D+)/g, function (_, , ) { ax.push([ || Infinity,  || ""]) });
   b.replace(/(\d+)|(\D+)/g, function (_, , ) { bx.push([ || Infinity,  || ""]) });

   while (ax.length && bx.length) {
     var an = ax.shift();
     var bn = bx.shift();
     var nn = (an[0] - bn[0]) || an[1].localeCompare(bn[1]);
     if (nn) return nn;
   }

   return ax.length - bx.length;
}

let builds = [ 
    { id: 1, name: 'Build 91'}, 
    { id: 2, name: 'Build 32' }, 
    { id: 3, name: 'Build 13' }, 
    { id: 4, name: 'Build 24' },
    { id: 5, name: 'Build 5' },
    { id: 6, name: 'Build 56' }
]

let sortedBuilds = builds.sort((n1, n2) => {
  return naturalCompare(n1.name, n2.name)
})

console.log('Sorted by name property')
console.log(sortedBuilds)

回答by Rafael Fraga Walter

The easiest way seems to be subtracting the second number from the first:

最简单的方法似乎是从第一个数字中减去第二个数字:

var numericArray:Array<number> = [2,3,4,1,5,8,11];

var sorrtedArray:Array<number> = numericArray.sort((n1,n2) => n1 - n2);

https://alligator.io/js/array-sort-numbers/

https://alligator.io/js/array-sort-numbers/

回答by Ashika

function naturalCompare(a, b) {
   var ax = [], bx = [];

   a.replace(/(\d+)|(\D+)/g, function (_, , ) { ax.push([ || Infinity,  || ""]) });
   b.replace(/(\d+)|(\D+)/g, function (_, , ) { bx.push([ || Infinity,  || ""]) });

   while (ax.length && bx.length) {
     var an = ax.shift();
     var bn = bx.shift();
     var nn = (an[0] - bn[0]) || an[1].localeCompare(bn[1]);
     if (nn) return nn;
   }

   return ax.length - bx.length;
}

let builds = [ 
    { id: 1, name: 'Build 91'}, 
    { id: 2, name: 'Build 32' }, 
    { id: 3, name: 'Build 13' }, 
    { id: 4, name: 'Build 24' },
    { id: 5, name: 'Build 5' },
    { id: 6, name: 'Build 56' }
]

let sortedBuilds = builds.sort((n1, n2) => {
  return naturalCompare(n1.name, n2.name)
})

console.log('Sorted by name property')
console.log(sortedBuilds)