我一直在各种项目中使用这个实用程序,而且效果很好。它也非常模块化:
传递要排序的键的名称选择排序是升序还是降序
按KeyUtil.js排序对象数组
// Sort array of objects by key
// ------------------------------------------------------------
const sortArrayOfObjsByKey = (array, key, ascdesc) =>
array.sort((a, b) => {
const x = a[key];
const y = b[key];
if (ascdesc === 'asc') {
return x < y ? -1 : x > y ? 1 : 0;
}
if (ascdesc === 'desc') {
return x > y ? -1 : x < y ? 1 : 0;
}
return null;
});
按KeyUtil.test.js排序对象数组
import sortArrayOfObjsByKey from './sortArrayOfObjsByKeyUtil';
const unsortedArray = [
{
_id: '3df55221-ce5c-4147-8e14-32effede6133',
title: 'Netlife Design',
address: {
PostalAddress: {
streetAddress: 'Youngstorget 3',
addressLocality: 'Oslo',
addressRegion: null,
postalCode: '0181',
addressCountry: 'Norway',
},
},
geopoint: { lat: 59.914322, lng: 10.749272 },
},
{
_id: 'cd00459f-3755-49f1-8847-66591ef935b2',
title: 'Home',
address: {
PostalAddress: {
streetAddress: 'Stockfleths gate 58A',
addressLocality: 'Oslo',
addressRegion: null,
postalCode: '0461',
addressCountry: 'Norway',
},
},
geopoint: { lat: 59.937316, lng: 10.751862 },
},
];
const sortedArray = [
{
_id: 'cd00459f-3755-49f1-8847-66591ef935b2',
title: 'Home',
address: {
PostalAddress: {
streetAddress: 'Stockfleths gate 58A',
addressLocality: 'Oslo',
addressRegion: null,
postalCode: '0461',
addressCountry: 'Norway',
},
},
geopoint: { lat: 59.937316, lng: 10.751862 },
},
{
_id: '3df55221-ce5c-4147-8e14-32effede6133',
title: 'Netlife Design',
address: {
PostalAddress: {
streetAddress: 'Youngstorget 3',
addressLocality: 'Oslo',
addressRegion: null,
postalCode: '0181',
addressCountry: 'Norway',
},
},
geopoint: { lat: 59.914322, lng: 10.749272 },
},
];
describe('sortArrayOfObjsByKey', () => {
it(`sort array by 'title' key, ascending`, () => {
const testInput = sortArrayOfObjsByKey(unsortedArray, 'title', 'asc');
const testOutput = sortedArray;
expect(testInput).toEqual(testOutput);
});
});