在javascript中基于所选值的反向数组列表



我有一个对象数组,如下所示

var arr = [{
DocumentNo: '44',
FileId: 1,
FilenameWithExtension: 'aof.tif',
DocTypeId: 1
}, {
DocumentNo: '45',
FileId: 2,
FilenameWithExtension: 'aofd.tif',
DocTypeId: 1
}, {
DocumentNo: '46',
FileId: 3,
FilenameWithExtension: 'mdh.tif',
DocTypeId: 1
}, {
DocumentNo: '47',
FileId: 4,
FilenameWithExtension: 'zyl.tif',
DocTypeId: 1
}, {
DocumentNo: '48',
FileId: 5,
FilenameWithExtension: 'ddd.tif',
DocTypeId: 3
}]

我想根据用户选择的内容反转数组,

例如

如果用户按降序选择documentno,上面的列表应该以documentno ->(48,47,46,45,44)开头

如果用户按升序选择字段,上面的列表应该开始(1,2,3,4,5)

如果用户按降序选择字段,上面的列表应该

以FileId ->(5,4,3,2,1)开头

等等

我怎么能达到同样的,我谷歌这个,但找不到任何

根据我的理解,您希望根据用户传递的fieldsorting order对该对象数组进行排序。如果是,下面是演示:

var arr = [{
DocumentNo: '44',
FileId: 1,
FilenameWithExtension: 'aof.tif',
DocTypeId: 1
}, {
DocumentNo: '45',
FileId: 2,
FilenameWithExtension: 'aofd.tif',
DocTypeId: 1
}, {
DocumentNo: '46',
FileId: 3,
FilenameWithExtension: 'mdh.tif',
DocTypeId: 1
}, {
DocumentNo: '47',
FileId: 4,
FilenameWithExtension: 'zyl.tif',
DocTypeId: 1
}, {
DocumentNo: '48',
FileId: 5,
FilenameWithExtension: 'ddd.tif',
DocTypeId: 3
}]
const sortingObj = {
field: 'FilenameWithExtension',
sortBy: 'desc'
};
const res = arr.sort((a, b) => {
if (sortingObj.field === 'FilenameWithExtension') {
if (sortingObj.sortBy === 'aesc') {
return (a[sortingObj.field] < b[sortingObj.field]) ? -1 : ((a[sortingObj.field] > b[sortingObj.field]) ? 1 : 0);
} else {
return (a[sortingObj.field] < b[sortingObj.field]) ? 1 : ((a[sortingObj.field] > b[sortingObj.field]) ? -1 : 0);
}
} else {
return (sortingObj.sortBy === 'aesc') ?
a[sortingObj.field] - b[sortingObj.field] :
b[sortingObj.field] - a[sortingObj.field]
}
});
console.log(res);

下面是一个关于如何使用下划线

的示例
let arr = [{
DocumentNo: '44',
FileId: 1,
FilenameWithExtension: 'aof.tif',
DocTypeId: 1
}, {
DocumentNo: '45',
FileId: 2,
FilenameWithExtension: 'aofd.tif',
DocTypeId: 1
}, {
DocumentNo: '46',
FileId: 3,
FilenameWithExtension: 'mdh.tif',
DocTypeId: 1
}, {
DocumentNo: '47',
FileId: 4,
FilenameWithExtension: 'zyl.tif',
DocTypeId: 1
}, {
DocumentNo: '48',
FileId: 5,
FilenameWithExtension: 'ddd.tif',
DocTypeId: 3
}];
let userInput = "DocTypeId";
let result = _.sortBy(arr, userInput);
console.log(result);
<script src="http://underscorejs.org/underscore.js"></script>

最新更新