Home > other >  Re arrange array of objects by specific value at top?
Re arrange array of objects by specific value at top?

Time:06-09

var objs = [ 
    { Product: 'Lazslo', Status: Approved     },
    { Product: 'Pig',    Status: Rejected  },
    { Product: 'Pirate',Status: Pending }
];

How can I sort them by the Status in JavaScript?

I know about sort(a,b), but that only seems to work on asc or desc ?

My output want like this

[        { Product: 'Pirate',Status: Pending }
         { Product: 'Lazslo', Status: Approved     },
         { Product: 'Pig',   Status: Rejected  },
        
       
       
    ];

CodePudding user response:

You can define priority for every status using an object and sort the array using Array#sort:

const statusScores = { 'Pending': 3, 'Rejected': 2, 'Approved': 1 };
const arr = [ { Product: 'Lazslo', Status: 'Approved' }, { Product: 'Pig', Status: 'Rejected' }, { Product: 'Pirate', Status: 'Pending' } ];

const res = arr.sort(({ Status: a }, { Status: b }) => statusScores[b] - statusScores[a]);

console.log(res);

CodePudding user response:

var objs = [ 
    { Product: 'Lazslo', Status: "Approved" },
    { Product: 'Pig',    Status: "Rejected" },
    { Product: 'Pirate', Status: "Pending"  }
];

var priority = ["Pending", "Approved", "Rejected"];

objs.sort( ( a, b ) => priority.indexOf( a.Status ) - priority.indexOf( b.Status ) );

console.log(objs);

Could be refactored to be reusable as such:

var objs = [ 
    { Product: 'Lazslo', Status: "Approved" },
    { Product: 'Pig',    Status: "Rejected" },
    { Product: 'Pirate', Status: "Pending"  }
];

var statusPriority = ["Pending", "Approved", "Rejected"];

const sortBy = (arr, priorityArr, propertyName) => 
  arr.sort( ( a, b ) => priorityArr.indexOf( a[propertyName] ) - priorityArr.indexOf( b[propertyName] ) );

console.log(sortBy(objs, statusPriority, "Status"));

  • Related