Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading