简体   繁体   English

按具有日期值的单个键对对象数组进行排序

[英]Sort array of objects by single key with date value

I have an array of objects with several key value pairs, and I need to sort them based on 'updated_at':我有一个包含多个键值对的对象数组,我需要根据“updated_at”对它们进行排序:

[
    {
        "updated_at" : "2012-01-01T06:25:24Z",
        "foo" : "bar"
    },
    {
        "updated_at" : "2012-01-09T11:25:13Z",
        "foo" : "bar"
    },
    {
        "updated_at" : "2012-01-05T04:13:24Z",
        "foo" : "bar"
    }
]

What's the most efficient way to do so?这样做的最有效方法是什么?

You can use Array.sort .您可以使用Array.sort

Here's an example:下面是一个例子:

 var arr = [{ "updated_at": "2012-01-01T06:25:24Z", "foo": "bar" }, { "updated_at": "2012-01-09T11:25:13Z", "foo": "bar" }, { "updated_at": "2012-01-05T04:13:24Z", "foo": "bar" } ] arr.sort(function(a, b) { var keyA = new Date(a.updated_at), keyB = new Date(b.updated_at); // Compare the 2 dates if (keyA < keyB) return -1; if (keyA > keyB) return 1; return 0; }); console.log(arr);

I already answered a really similar question here: Simple function to sort an array of objects我已经在这里回答了一个非常相似的问题: Simple function to sort an array of objects

For that question I created this little function that might do what you want:对于那个问题,我创建了这个小函数,它可能会做你想做的事:

function sortByKey(array, key) {
    return array.sort(function(a, b) {
        var x = a[key]; var y = b[key];
        return ((x < y) ? -1 : ((x > y) ? 1 : 0));
    });
}

The Array.sort() method sorts the elements of an array in place and returns the array. Array.sort()方法对数组的元素进行原地排序并返回数组。 Be careful with Array.sort() as it's not Immutable .小心Array.sort()因为它不是Immutable For immutable sort use immutable-sort .对于不可变排序,请使用immutable-sort

This method is to sort the array using your current updated_at in ISO format.此方法是使用 ISO 格式的当前updated_at对数组进行排序。 We use new Data(iso_string).getTime() to convert ISO time to Unix timestamp.我们使用new Data(iso_string).getTime()将 ISO 时间转换为 Unix 时间戳。 A Unix timestamp is a number that we can do simple math on. Unix 时间戳是一个我们可以做简单数学运算的数字。 We subtract the first and second timestamp the result is;我们减去第一个和第二个时间戳,结果是; if the first timestamp is bigger than the second the return number will be positive.如果第一个时间戳大于第二个,则返回数字将为正。 If the second number is bigger than the first the return value will be negative.如果第二个数字大于第一个,则返回值将为负数。 If the two are the same the return will be zero.如果两者相同,则返回为零。 This alines perfectly with the required return values for the inline function.这与内联函数所需的返回值完全一致。

For ES6 :对于ES6

arr.sort((a,b) => new Date(a.updated_at).getTime() - new Date(b.updated_at).getTime());

For ES5 :对于ES5

arr.sort(function(a,b){ 
 return new Date(a.updated_at).getTime() - new Date(b.updated_at).getTime();
});

If you change your updated_at to be unix timestamps you can do this:如果您将updated_at更改为 unix 时间戳,您可以执行以下操作:

For ES6 :对于ES6

arr.sort((a,b) => a.updated_at - b.updated_at);

For ES5 :对于ES5

arr.sort(function(a,b){ 
 return a.updated_at - b.updated_at;
});

At the time of this post, modern browsers do not support ES6.在撰写本文时,现代浏览器不支持 ES6。 To use ES6 in modern browsers use babel to transpile the code to ES5.要在现代浏览器中使用 ES6,请使用babel将代码转换为 ES5。 Expect browser support for ES6 in the near future.期待浏览器在不久的将来支持 ES6。

Array.sort() should receave a return value of one of 3 possible outcomes: Array.sort()应该接收 3 种可能结果之一的返回值:

  • A positive number (first item > second item)一个正数(第一项 > 第二项)
  • A negative number (first item < second item)负数(第一项 < 第二项)
  • 0 if the two items are equal 0 如果两项相等

Note that the return value on the inline function can be any positive or negative number.请注意,内联函数的返回值可以是任何正数或负数。 Array.Sort() does not care what the return number is. Array.Sort() 不关心返回数字是什么。 It only cares if the return value is positive, negative or zero.它只关心返回值是正数、负数还是零。

For Immutable sort: (example in ES6)对于不可变排序:(以 ES6 为例)

const sort = require('immutable-sort');
const array = [1, 5, 2, 4, 3];
const sortedArray = sort(array);

You can also write it this way:你也可以这样写:

import sort from 'immutable-sort';
const array = [1, 5, 2, 4, 3];
const sortedArray = sort(array);

The import-from you see is a new way to include javascript in ES6 and makes your code look very clean.您看到的 import-from 是一种在 ES6 中包含 javascript 的新方法,并使您的代码看起来非常干净。 My personal favorite.我个人的最爱。

Immutable sort doesn't mutate the source array rather it returns a new array.不可变排序不会改变源数组,而是返回一个新数组。 Using const is recommended on immutable data.建议对不可变数据使用const

Here's a slightly modified version of @David Brainer-Bankers answer that sorts alphabetically by string, or numerically by number, and ensures that words beginning with Capital letters don't sort above words starting with a lower case letter (eg "apple,Early" would be displayed in that order).这是@David Brainer-Bankers 答案的略微修改版本,它按字符串或数字按字母顺序排序,并确保以大写字母开头的单词不会排在以小写字母开头的单词之上(例如“apple,Early”将按该顺序显示)。

function sortByKey(array, key) {
    return array.sort(function(a, b) {
        var x = a[key];
        var y = b[key];

        if (typeof x == "string")
        {
            x = (""+x).toLowerCase(); 
        }
        if (typeof y == "string")
        {
            y = (""+y).toLowerCase();
        }

        return ((x < y) ? -1 : ((x > y) ? 1 : 0));
    });
}

Use underscore js or lodash,使用下划线 js 或 lodash,

var arrObj = [
    {
        "updated_at" : "2012-01-01T06:25:24Z",
        "foo" : "bar"
    },
    {
        "updated_at" : "2012-01-09T11:25:13Z",
        "foo" : "bar"
    },
    {
        "updated_at" : "2012-01-05T04:13:24Z",
        "foo" : "bar"
    }
];

arrObj = _.sortBy(arrObj,"updated_at");

_.sortBy() returns a new array _.sortBy()返回一个新数组

refer http://underscorejs.org/#sortBy and lodash docs https://lodash.com/docs#sortBy参考http://underscorejs.org/#sortBy和 lodash 文档https://lodash.com/docs#sortBy

有了 ES2015 支持,它可以通过以下方式完成:

foo.sort((a, b) => a.updated_at < b.updated_at ? -1 : 1)

Data Imported数据导入

[
    {
        "gameStatus": "1",
        "userId": "c02cfb18-ae66-430b-9524-67d9dd8f6a50",
        "created_at": "2018-12-20 11:32:04"
    },
    {
        "gameStatus": "0",
        "userId": "c02cfb18-ae66-430b-9524-67d9dd8f6a50",
        "created_at": "2018-12-19 18:08:24"
    },
    {
        "gameStatus": "2",
        "userId": "c02cfb18-ae66-430b-9524-67d9dd8f6a50",
        "created_at": "2018-12-19 18:35:40"
    },
    {
        "gameStatus": "0",
        "userId": "c02cfb18-ae66-430b-9524-67d9dd8f6a50",
        "created_at": "2018-12-19 10:42:53"
    },
    {
        "gameStatus": "2",
        "userId": "c02cfb18-ae66-430b-9524-67d9dd8f6a50",
        "created_at": "2018-12-20 10:54:09"
    },
    {
        "gameStatus": "0",
        "userId": "1a2fefb0-5ae2-47eb-82ff-d1b2cc27875a",
        "created_at": "2018-12-19 18:46:22"
    },
    {
        "gameStatus": "1",
        "userId": "7118ed61-d8d9-4098-a81b-484158806d21",
        "created_at": "2018-12-20 10:50:48"
    }
]

FOR Ascending order FOR 升序

arr.sort(function(a, b){
    var keyA = new Date(a.updated_at),
        keyB = new Date(b.updated_at);
    // Compare the 2 dates
    if(keyA < keyB) return -1;
    if(keyA > keyB) return 1;
    return 0;
});

Example for Asc Order升序示例

[
    {
        "gameStatus": "0",
        "userId": "c02cfb18-ae66-430b-9524-67d9dd8f6a50",
        "created_at": "2018-12-19 10:42:53"
    },
    {
        "gameStatus": "0",
        "userId": "c02cfb18-ae66-430b-9524-67d9dd8f6a50",
        "created_at": "2018-12-19 18:08:24"
    },
    {
        "gameStatus": "2",
        "userId": "c02cfb18-ae66-430b-9524-67d9dd8f6a50",
        "created_at": "2018-12-19 18:35:40"
    },
    {
        "gameStatus": "0",
        "userId": "1a2fefb0-5ae2-47eb-82ff-d1b2cc27875a",
        "created_at": "2018-12-19 18:46:22"
    },
    {
        "gameStatus": "1",
        "userId": "7118ed61-d8d9-4098-a81b-484158806d21",
        "created_at": "2018-12-20 10:50:48"
    },
    {
        "gameStatus": "2",
        "userId": "c02cfb18-ae66-430b-9524-67d9dd8f6a50",
        "created_at": "2018-12-20 10:54:09"
    },
    {
        "gameStatus": "1",
        "userId": "c02cfb18-ae66-430b-9524-67d9dd8f6a50",
        "created_at": "2018-12-20 11:32:04"
    }
]

FOR Descending order FOR 降序

arr.sort(function(a, b){
    var keyA = new Date(a.updated_at),
        keyB = new Date(b.updated_at);
    // Compare the 2 dates
    if(keyA > keyB) return -1;
    if(keyA < keyB) return 1;
    return 0;
});

Example for Desc Order降序示例

[
    {
        "gameStatus": "1",
        "userId": "c02cfb18-ae66-430b-9524-67d9dd8f6a50",
        "created_at": "2018-12-20 11:32:04"
    },
    {
        "gameStatus": "2",
        "userId": "c02cfb18-ae66-430b-9524-67d9dd8f6a50",
        "created_at": "2018-12-20 10:54:09"
    },
    {
        "gameStatus": "1",
        "userId": "7118ed61-d8d9-4098-a81b-484158806d21",
        "created_at": "2018-12-20 10:50:48"
    },
    {
        "gameStatus": "0",
        "userId": "1a2fefb0-5ae2-47eb-82ff-d1b2cc27875a",
        "created_at": "2018-12-19 18:46:22"
    },
    {
        "gameStatus": "2",
        "userId": "c02cfb18-ae66-430b-9524-67d9dd8f6a50",
        "created_at": "2018-12-19 18:35:40"
    },
    {
        "gameStatus": "0",
        "userId": "c02cfb18-ae66-430b-9524-67d9dd8f6a50",
        "created_at": "2018-12-19 18:08:24"
    },
    {
        "gameStatus": "0",
        "userId": "c02cfb18-ae66-430b-9524-67d9dd8f6a50",
        "created_at": "2018-12-19 10:42:53"
    }
]

As This answer's states, you can use Array.sort .由于答案的状态,你可以使用Array.sort

arr.sort(function(a,b){return new Date(a.updated_at) - new Date(b.updated_at)})

 arr = [ { "updated_at" : "2012-01-01T06:25:24Z", "foo" : "bar" }, { "updated_at" : "2012-01-09T11:25:13Z", "foo" : "bar" }, { "updated_at" : "2012-01-05T04:13:24Z", "foo" : "bar" } ]; arr.sort(function(a,b){return new Date(a.updated_at) - new Date(b.updated_at)}); console.log(arr);

As for today, answers of @knowbody ( https://stackoverflow.com/a/42418963/6778546 ) and @Rocket Hazmat ( https://stackoverflow.com/a/8837511/6778546 ) can be combined to provide for ES2015 support and correct date handling:至于今天,@knowbody ( https://stackoverflow.com/a/42418963/6778546 ) 和@Rocket Hazmat ( https://stackoverflow.com/a/8837511/6778546 ) 的答案可以结合起来提供 ES2015 支持和正确的日期处理:

arr.sort((a, b) => {
   const dateA = new Date(a.updated_at);
   const dateB = new Date(b.updated_at);
   return dateA - dateB;
});

You could use the Lodash utility library to solve this problem (it's quite an efficient library):您可以使用Lodash实用程序库来解决这个问题(它是一个非常高效的库):

 const data = [{ "updated_at": "2012-01-01T06:25:24Z", "foo": "bar" }, { "updated_at": "2012-01-09T11:25:13Z", "foo": "bar" }, { "updated_at": "2012-01-05T04:13:24Z", "foo": "bar" } ] const ordered = _.orderBy( data, function(item) { return item.updated_at; } ); console.log(ordered)
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>

You can find documentation here: https://lodash.com/docs/4.17.15#orderBy您可以在此处找到文档: https : //lodash.com/docs/4.17.15#orderBy

Just another, more mathematical , way of doing the same thing but shorter :只是另一种更数学化的做同样事情但更短的方法

arr.sort(function(a, b){
    var diff = new Date(a.updated_at) - new Date(b.updated_at);
    return diff/(Math.abs(diff)||1);
});

or in the slick lambda arrow style:或在光滑的 lambda 箭头样式中:

arr.sort((a, b) => {
    var diff = new Date(a.updated_at) - new Date(b.updated_at);
    return diff/(Math.abs(diff)||1);
});

This method can be done with any numeric input这种方法可以用任何数字输入来完成

With this we can pass a key function to use for the sorting有了这个,我们可以传递一个键函数来用于排序

Array.prototype.sortBy = function(key_func, reverse=false){
    return this.sort( (a, b) => {
        var keyA = key_func(a),
            keyB = key_func(b);
        if(keyA < keyB) return reverse? 1: -1;
        if(keyA > keyB) return reverse? -1: 1;
        return 0;
    }); 
}

Then for example if we have然后例如如果我们有

var arr = [ {date: "01/12/00", balls: {red: "a8",  blue: 10}},
            {date: "12/13/05", balls: {red: "d6" , blue: 11}},
            {date: "03/02/04", balls: {red: "c4" , blue: 15}} ]

We can do我们可以做的

arr.sortBy(el => el.balls.red)
/* would result in
[ {date: "01/12/00", balls: {red: "a8", blue: 10}},
  {date: "03/02/04", balls: {red: "c4", blue: 15}},
  {date: "12/13/05", balls: {red: "d6", blue: 11}} ]
*/

or要么

arr.sortBy(el => new Date(el.date), true)   // second argument to reverse it
/* would result in
[ {date: "12/13/05", balls: {red: "d6", blue:11}},
  {date: "03/02/04", balls: {red: "c4", blue:15}},
  {date: "01/12/00", balls: {red: "a8", blue:10}} ]
*/

or要么

arr.sortBy(el => el.balls.blue + parseInt(el.balls.red[1]))
/* would result in
[ {date: "12/13/05", balls: {red: "d6", blue:11}},    // red + blue= 17
  {date: "01/12/00", balls: {red: "a8", blue:10}},    // red + blue= 18
  {date: "03/02/04", balls: {red: "c4", blue:15}} ]   // red + blue= 19
*/

I have created a sorting function in Typescript which we can use to search strings, dates and numbers in array of objects.我在 Typescript 中创建了一个排序函数,我们可以用它来搜索对象数组中的字符串、日期和数字。 It can also sort on multiple fields.它还可以对多个字段进行排序。

export type SortType = 'string' | 'number' | 'date';
export type SortingOrder = 'asc' | 'desc';

export interface SortOptions {
  sortByKey: string;
  sortType?: SortType;
  sortingOrder?: SortingOrder;
}


class CustomSorting {
    static sortArrayOfObjects(fields: SortOptions[] = [{sortByKey: 'value', sortType: 'string', sortingOrder: 'desc'}]) {
        return (a, b) => fields
          .map((field) => {
            if (!a[field.sortByKey] || !b[field.sortByKey]) {
              return 0;
            }

            const direction = field.sortingOrder === 'asc' ? 1 : -1;

            let firstValue;
            let secondValue;

            if (field.sortType === 'string') {
              firstValue = a[field.sortByKey].toUpperCase();
              secondValue = b[field.sortByKey].toUpperCase();
            } else if (field.sortType === 'number') {
              firstValue = parseInt(a[field.sortByKey], 10);
              secondValue = parseInt(b[field.sortByKey], 10);
            } else if (field.sortType === 'date') {
              firstValue = new Date(a[field.sortByKey]);
              secondValue = new Date(b[field.sortByKey]);
            }
            return firstValue > secondValue ? direction : firstValue < secondValue ? -(direction) : 0;

          })
          .reduce((pos, neg) => pos ? pos : neg, 0);
      }
    }
}

Usage:用法:

const sortOptions = [{
      sortByKey: 'anyKey',
      sortType: 'string',
      sortingOrder: 'asc',
    }];

arrayOfObjects.sort(CustomSorting.sortArrayOfObjects(sortOptions));

For completeness here is a possible short generic implementation of sortBy:为了完整起见,这里是 sortBy 的一个可能的简短通用实现:

function sortBy(list, keyFunc) {
  return list.sort((a,b) => keyFunc(a) - keyFunc(b));
}

sortBy([{"key": 2}, {"key": 1}], o => o["key"])

Note that this uses the arrays sort method that sorts in place.请注意,这使用了就地排序的数组排序方法。 for a copy you can use arr.concat() or arr.slice(0) or similar method to create a copy.对于副本,您可以使用 arr.concat() 或 arr.slice(0) 或类似方法来创建副本。

Sorting by an ISO formatted date can be expensive, unless you limit the clients to the latest and best browsers, which can create the correct timestamp by Date-parsing the string.按 ISO 格式的日期排序可能很昂贵,除非您将客户端限制为最新和最好的浏览器,这可以通过对字符串进行日期解析来创建正确的时间戳。

If you are sure of your input, and you know it will always be yyyy-mm-ddThh:mm:ss and GMT (Z) you can extract the digits from each member and compare them like integers如果您确定您的输入,并且您知道它始终是 yyyy-mm-ddThh:mm:ss 和 GMT (Z),您可以从每个成员中提取数字并将它们作为整数进行比较

array.sort(function(a,b){
    return a.updated_at.replace(/\D+/g,'')-b.updated_at.replace(/\D+/g,'');
});

If the date could be formatted differently, you may need to add something for iso challenged folks:如果日期的格式可以不同,您可能需要为 iso 挑战的人添加一些内容:

Date.fromISO: function(s){
    var day, tz,
    rx=/^(\d{4}\-\d\d\-\d\d([tT ][\d:\.]*)?)([zZ]|([+\-])(\d\d):(\d\d))?$/,
    p= rx.exec(s) || [];
    if(p[1]){
        day= p[1].split(/\D/).map(function(itm){
            return parseInt(itm, 10) || 0;
        });
        day[1]-= 1;
        day= new Date(Date.UTC.apply(Date, day));
        if(!day.getDate()) return NaN;
        if(p[5]){
            tz= (parseInt(p[5], 10)*60);
            if(p[6]) tz+= parseInt(p[6], 10);
            if(p[4]== '+') tz*= -1;
            if(tz) day.setUTCMinutes(day.getUTCMinutes()+ tz);
        }
        return day;
    }
    return NaN;
}
if(!Array.prototype.map){
    Array.prototype.map= function(fun, scope){
        var T= this, L= T.length, A= Array(L), i= 0;
        if(typeof fun== 'function'){
            while(i< L){
                if(i in T){
                    A[i]= fun.call(scope, T[i], i, T);
                }
                ++i;
            }
            return A;
        }
    }
}
}

You can create a closure and pass it that way here is my example working您可以创建一个闭包并以这种方式传递它,这是我的示例工作

$.get('https://data.seattle.gov/resource/3k2p-39jp.json?$limit=10&$where=within_circle(incident_location, 47.594972, -122.331518, 1609.34)', 
  function(responce) {

    var filter = 'event_clearance_group', //sort by key group name
    data = responce; 

    var compare = function (filter) {
        return function (a,b) {
            var a = a[filter],
                b = b[filter];

            if (a < b) {
                return -1;
            } else if (a > b) {
                return 1;
            } else {
                return 0;
            }
        };
    };

    filter = compare(filter); //set filter

    console.log(data.sort(filter));
});
var months = [
    {
        "updated_at" : "2012-01-01T06:25:24Z",
        "foo" : "bar"
    },
    {
        "updated_at" : "2012-01-09T11:25:13Z",
        "foo" : "bar"
    },
    {
        "updated_at" : "2012-01-05T04:13:24Z",
        "foo" : "bar"
    }];
months.sort((a, b)=>{
    var keyA = new Date(a.updated_at),
        keyB = new Date(b.updated_at);
    // Compare the 2 dates
    if(keyA < keyB) return -1;
    if(keyA > keyB) return 1;
    return 0;
});
console.log(months);
  • Use Array.sort() to sort an array使用Array.sort()对数组进行排序
  • Clone array using spread operator ( ) to make the function pure使用扩展运算符( ) 克隆数组以使函数纯
  • Sort by desired key ( updated_at )按所需键排序( updated_at
  • Convert date string to date object将日期字符串转换为日期对象
  • Array.sort() works by subtracting two properties from current and next item if it is a number / object on which you can perform arrhythmic operations Array.sort()通过从当前和下一个项目中减去两个属性来工作,如果它是一个数字/对象,您可以对其执行心律失常操作
const input = [
  {
    updated_at: '2012-01-01T06:25:24Z',
    foo: 'bar',
  },
  {
    updated_at: '2012-01-09T11:25:13Z',
    foo: 'bar',
  },
  {
    updated_at: '2012-01-05T04:13:24Z',
    foo: 'bar',
  }
];

const sortByUpdatedAt = (items) => [...items].sort((itemA, itemB) => new Date(itemA.updated_at) - new Date(itemB.updated_at));

const output = sortByUpdatedAt(input);

console.log(input);
/*
[ { updated_at: '2012-01-01T06:25:24Z', foo: 'bar' }, 
  { updated_at: '2012-01-09T11:25:13Z', foo: 'bar' }, 
  { updated_at: '2012-01-05T04:13:24Z', foo: 'bar' } ]
*/
console.log(output)
/*
[ { updated_at: '2012-01-01T06:25:24Z', foo: 'bar' }, 
  { updated_at: '2012-01-05T04:13:24Z', foo: 'bar' }, 
  { updated_at: '2012-01-09T11:25:13Z', foo: 'bar' } ]
*/

I face with same thing, so i handle this with a generic why and i build a function for this:我面临同样的事情,所以我用一个通用的原因来处理这个问题,并为此构建了一个函数:

 //example: //array: [{name: 'idan', workerType: '3'}, {name: 'stas', workerType: '5'}, {name: 'kirill', workerType: '2'}] //keyField: 'workerType' // keysArray: ['4', '3', '2', '5', '6']
sortByArrayOfKeys = (array, keyField, keysArray) => {
    array.sort((a, b) => {
        const aIndex = keysArray.indexOf(a[keyField])
        const bIndex = keysArray.indexOf(b[keyField])
        if (aIndex < bIndex) return -1;
        if (aIndex > bIndex) return 1;
        return 0;
    })
}

 const arr = [ { "updated_at" : "2012-01-01T06:25:24Z", "foo" : "bar" }, { "updated_at" : "2012-01-09T11:25:13Z", "foo" : "bar" }, { "updated_at" : "2012-01-05T04:13:24Z", "foo" : "bar" } ] console.log("Before Sorting ", arr) arr.sort((a,b)=> (a.updated_at - b.updated_at) ? 1 : -1) console.log("After Sorting ", arr)

I'm getting here a little late, but in 2021 the correct answer is to use Intl.Collator .我来得有点晚,但在 2021 年,正确的答案是使用Intl.Collator updated_at is an ISO-8601 string and thus sortable as a string. updated_at是一个 ISO-8601 字符串,因此可以作为字符串进行排序。 Converting to a Date is a waste of time and so is performing if comparisons manually to return 0, 1, or -1.转换为Date是浪费时间,因此if手动比较以返回 0、1 或 -1,则执行此操作也是浪费时间。

const arr = [
  {
    "updated_at": "2012-01-01T06:25:24Z",
    "foo": "bar"
  },
  {
    "updated_at": "2012-01-09T11:25:13Z",
    "foo": "bar"
  },
  {
    "updated_at": "2012-01-05T04:13:24Z",
    "foo": "bar"
  }
];

const { compare } = Intl.Collator('en-US');
arr.sort((a, b) => compare(a.updated_at, b.updated_at));

Intl.Collator returns a function that can be used as the compareFunction for #Array.sort . Intl.Collator返回一个函数,该函数可用作#Array.sortcompareFunction Because we're sorting an object, we call compare with the values of the key that we want to sort by.因为我们正在对一个对象进行排序,所以我们调用compare与我们想要排序的键的值。

Note that if we were sorting an array of strings, we could simply do this:请注意,如果我们对字符串数组进行排序,我们可以简单地这样做:

arr.sort(compare);

Also note that as others have pointed out, sort will mutate the original array.另请注意,正如其他人指出的那样, sort会改变原始数组。 If this is undesirable, you may want to clone it first.如果这是不可取的,您可能需要先克隆它。 In 2021 you can do so as follows:在 2021 年,您可以这样做:

[...arr].sort((a, b) => compare(a.updated_at, b.updated_at));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM