reverse array list based on selected value in javascript

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

>Solution :

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: 'DocumentNo',
  sortBy: 'desc'
};

const res = arr.sort((a, b) => {
  return (sortingObj.sortBy === 'aesc') ?
    a[sortingObj[field]] - b[sortingObj.field] :
    b[sortingObj.field] - a[sortingObj.field]
});

console.log(res);

Leave a Reply