I have an object array which looks like below
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
}]
I want to reverse the array based on what user selects,
for example
if user selects documentno in descending order the above list should starts with documentno ->(48,47,46,45,44)
if user selects fileid in ascending order the above list should starts with FileId ->(1,2,3,4,5)
if user selects fileid in descending order the above list should starts with FileId ->(5,4,3,2,1)
and so on.
how can I achieve the same, I googled this but couldn't found anything
As per my understanding you want to sort this array of objects based on the field and sorting order passed by the user. If Yes, Here is the demo :
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);
Here's an example on how to do that with underscore
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>