itsource

날짜 값이 있는 단일 키를 기준으로 개체 배열 정렬

mycopycode 2022. 9. 6. 22:32
반응형

날짜 값이 있는 단일 키를 기준으로 개체 배열 정렬

여러 개의 키 값 쌍을 가진 개체 배열이 있으며 '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"
    }
]

가장 효율적인 방법은 무엇입니까?

를 사용할 수 있습니다.

다음은 예를 제시하겠습니다.

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

나는 이미 매우 유사한 질문에 대답했습니다: 객체 배열을 정렬하는 간단한 기능

이 질문에 대해 저는 여러분이 원하는 것을 할 수 있는 작은 함수를 만들었습니다.

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

Array.sort() 메서드는 배열 요소를 정렬하고 배열을 반환합니다.Array.sort()불변하지 않으므로 주의하십시오.불변의 종류에는 불변의 종류를 사용한다.

은 현재 하고 있는 입니다.updated_atISO 식 iso iso iso iso iso iso는 용용 we we we we we we we we wenew Data(iso_string).getTime()ISO Unix iso iso iso 。Unix 타임스탬프는 간단한 계산을 할 수 있는 숫자입니다.첫 번째 타임스탬프와 두 번째 타임스탬프를 뺍니다.첫 번째 타임스탬프가 두 번째 타임스탬프보다 클 경우 반환 번호는 양의 값이 됩니다.두 번째 숫자가 첫 번째 숫자보다 클 경우 반환값은 음수가 됩니다.두 개의 값이 같을 경우 수익률은 0이 됩니다.이는 인라인 함수에 필요한 반환값에 따라 완벽하게 달라집니다.

ES6의 경우:

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

ES5의 경우:

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

updated_at과 같이할 수 .

ES6의 경우:

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

ES5의 경우:

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

현재 최신 브라우저는 ES6를 지원하지 않습니다.최신 브라우저에서 ES6를 사용하려면 babel을 사용하여 코드를 ES5로 변환합니다.가까운 장래에 ES6에 대한 브라우저 지원이 예상됩니다.

Array.sort()는 다음 3가지 결과 중 하나를 반환해야 합니다.

  • 양수(첫 번째 항목 > 두 번째 항목)
  • 음수(첫 번째 항목 < 두 번째 항목)
  • 두 항목이 동일한 경우 0

인라인 함수의 반환값은 양수 또는 음수 중 어느 것이라도 상관없습니다.Array.Sort()는 반환번호는 신경 쓰지 않습니다.이 값은 반환값이 양수인지 음수인지 0인지 여부만 상관합니다.

불변 정렬의 경우: (ES6의 예)

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

다음과 같이 쓸 수도 있습니다.

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

import-from은 javascript를 ES6에 포함시키는 새로운 방법으로 코드를 매우 깔끔하게 보이게 합니다.내가 제일 좋아하는 것.

불변 정렬은 소스 어레이를 변환하지 않고 새 어레이를 반환합니다.「」를 사용합니다.const는 불변 데이터에 권장됩니다.

여기 @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));
    });
}

밑줄 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()합니다.

http://underscorejs.org/ #sortBy 및 lodash 문서를 참조하십시오.https://lodash.com/docs#sortBy

ES2015 지원을 통해 다음을 수행할 수 있습니다.

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

데이터 Import

[
    {
        "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"
    }
]

오름차순의 경우

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

ASC 순서의 예

[
    {
        "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"
    }
]

내림차순의 경우

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

설명 순서 예시

[
    {
        "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"
    }
]

답변에서는 를 사용할 수 있습니다.

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

현재 @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;
});

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>

매뉴얼은 https://lodash.com/docs/4.17.15#orderBy 에서 찾을 수 있습니다.

조금 늦게 도착하지만 2021년에 정답은 을 사용하는 것입니다.updated_at는 ISO-8601 문자열이므로 문자열로 정렬할 수 있습니다.로의 Date이며, 도 시간낭비입니다.if0, 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 returns returns the the the the the the the the the the the로 할 수 합니다.compareFunction★★★★★★에#Array.sort에 콜을 compare정렬할 키의 값을 입력합니다.

문자열 배열을 정렬할 경우 다음과 같이 간단하게 할 수 있습니다.

arr.sort(compare);

다른 처럼 '하다'라는 은,sort는 원래의 어레이를 변환합니다.이것이 바람직하지 않은 경우는, 우선 클론을 작성할 필요가 있습니다.할 수 :2021 에 in in in in in in in in in in in in in in in in in in in in in in in in in in in in in in 。

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

같은 을 더 짧게 하는 또 다른 수학적인 방법:

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

또는 매끄러운 람다 화살표 스타일로:

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

이 방법은 모든 숫자 입력으로 수행할 수 있습니다.

이것으로 정렬에 사용할 주요 기능을 전달할 수 있습니다.

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

그럼 예를 들어,

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}} ]

할 수 있다

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}} ]
*/

또는

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}} ]
*/

또는

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
*/

오브젝트 배열의 문자열, 날짜, 숫자를 검색할 수 있는 정렬 기능을 Typescript에 만들었습니다.여러 필드에서 정렬할 수도 있습니다.

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

사용방법:

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

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

ISO 형식의 날짜로 정렬하는 것은 클라이언트를 최신 브라우저와 최적의 브라우저로 제한하지 않는 한 비용이 많이 들 수 있습니다.이 경우 문자열의 날짜 파싱을 통해 올바른 타임스탬프를 생성할 수 있습니다.

입력이 확실하고 항상 yyy-mm-dThh:mm:ss 및 GMT(Z)인 경우 각 멤버에서 숫자를 추출하여 정수처럼 비교할 수 있습니다.

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

날짜 형식이 다를 경우 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;
        }
    }
}
}

완전성을 위해 sortBy의 짧은 범용 구현을 다음에 나타냅니다.

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

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

이 방법에서는 정렬하는 배열 정렬 방식이 사용됩니다.복사에는 arr.concat() 또는 ar.concat(0) 또는 이와 유사한 방법을 사용할 수 있습니다.

  • 배열 정렬에 사용
  • 확산 연산자를 사용하여 어레이 클론 생성)기능을 순수하게 하다
  • 원하는 키에 따라 정렬합니다(updated_at)
  • 날짜 문자열을 날짜 개체로 변환
  • 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' } ]
*/

저도 같은 문제에 직면해 있기 때문에, 일반적인 이유를 가지고 대처하고, 이 문제를 위한 기능을 구축합니다.

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

폐쇄를 생성하여 전달할 수 있습니다. 이 예는 다음과 같습니다.

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

언급URL : https://stackoverflow.com/questions/8837454/sort-array-of-objects-by-single-key-with-date-value

반응형