我目前正在使用我的reactjs应用程序中的以下函数呈现我的用户列表。
我想以某种方式创建一个通用的排序函数,使我可以根据user对象上的不同属性对用户进行排序:
User
-id
-sortOrder
-dateCreated
-name
是否可以编写一个排序函数,然后我可以按id、sortOrder、dateCreated或name属性进行排序?
_renderUsers() {
const { users, dispatch } = this.props;
return users.map((user) => {
return (
<User
key={user.id}
dispatch={dispatch}
{...user}
/>
);
});
}
我在我的主渲染函数中调用它:
<div className="users-list">
{::this._renderUsers()}
</div>
发布于 2018-08-08 06:01:22
版本在方向和数值排序方面更具灵活性
const users = [
{ id: 4, sortOrder: "asc", dateCreated: "2016-01-01", name: "Foo" },
{ id: 2, sortOrder: "desc", dateCreated: "2014-01-01", name: "Bar" },
{ id: 1, sortOrder: "desc", dateCreated: "2015-01-01", name: "Test" }
];
function sortArr(arr, key, ascending = true) {
if (!isNaN(arr[0][key])) {
return arr.sort((a, b) => (ascending ? a[key] - b[key] : b[key] - a[key]))
} else {
return arr.sort((a, b) => {
const ref = ascending ? a[key] : b[key];
const comp = ascending ? b[key] : a[key];
return ref.localeCompare(comp);
});
}
}
LOG(sortArr(users, 'name', false)) // string names descending
LOG(sortArr(users, 'id')) // numeric id ascending
function LOG(d) {
console.log(JSON.stringify(d, null, ' '));
console.log('\n*******************************\n')
}
发布于 2018-08-08 05:36:21
您可以创建一个函数,该函数接受users
数组和一个字符串sortParam
,该字符串指示要使用哪个参数对它们进行排序。
const users = [
{ id: 4, sortOrder: "asc", dateCreated: "2016-01-01", name: "Foo" },
{ id: 2, sortOrder: "desc", dateCreated: "2014-01-01", name: "Bar" },
{ id: 1, sortOrder: "desc", dateCreated: "2015-01-01", name: "Test" }
];
function sortUsers(users, sortParam) {
return users.sort((a, b) => {
if (a[sortParam] < b[sortParam]) {
return -1;
}
if (a[sortParam] > b[sortParam]) {
return 1;
}
return 0;
});
}
console.log(sortUsers(users, 'id'))
发布于 2018-08-08 06:53:02
以下是一种允许您对任何字段使用localeCompare
的方法:
var users = [
{
id: 1,
name: 'Bob',
age: 13,
state: 'CA',
other: 'james1'
},
{
id: 2,
name: 'Ken',
age: 23,
state: 'AL',
other: 'james11'
},{
id: 3,
name: 'Alex',
age: 33,
state: 'NY',
other: 'kin 1'
},
{
id: 4,
name: 'Alex',
age: 83,
state: 'DC',
other: 'kin 110'
}
]
const sortBy = (array, field, options={ direction: 'asc' }) =>
array.sort((x,y) => (options.direction == 'desc' ? -1 : 1) * String(x[field]).localeCompare(String(y[field]), undefined, options))
console.log(sortBy(users, 'name')) // just by name
console.log(sortBy(users, 'state', { direction: 'desc' })) // change the direction
console.log(sortBy(users, 'age', { numeric: true })) // sorting numbers
console.log(sortBy(users, 'other', { numeric: true })) // notice how "other" values are ordered now
这允许您传递options object to localeCompare,以及更改最终订单的方向。使用此函数可以比较数字/字符串中的数字等。
为了改变排序顺序,我们只需将localeCompare
的结果乘以-1
或1
(取决于所需的方向)。
这里要付出的代价是使用localeCompare
的boxing to String
。
https://stackoverflow.com/questions/51735712
复制相似问题