Home > Enterprise >  how we can sort table as costume ordered values?
how we can sort table as costume ordered values?

Time:06-23

I want to sort the table based on costume values as below how we can write the logic for this from react side?

Order is no s, no c, ready, pub

as I want to sort the below data const data = [ { name: 'Harry', sort: 'no c', }, { name: 'Don', sort: 'no s', }, { name: 'Arc', sort: 'pub', }, { name: 'Park', sort: 'ready', }, ];

CodePudding user response:

You can create an array of sort value in order that you want to sort data, then use filter function to get those value and push it to output array.

E.g.

let output = []
let order = ['no s','no c','pub','ready']
const data = [ { name: 'Harry', sort: 'no c', }, { name: 'Don', sort: 'no s', }, { name: 'Arc', sort: 'pub', }, { name: 'Park', sort: 'ready', }]

for(const o of order){
    output.push(...data.filter(d=>d.sort === o))
}

console.log(output)

CodePudding user response:

const arr = [
  { name: 'Harry', sort: 'no c', }, 
  { name: 'Don', sort: 'no s', }, 
  { name: 'Arc', sort: 'pub', }, 
  { name: 'Park', sort: 'ready', }, 
];

const order = [ 'no s', 'no c', 'ready', 'pub'];

const orderedArr = [];

order.forEach(element => {
  const item = arr.find((obj) => obj.sort === element);
  orderedArr.push(item);
});

CodePudding user response:

The other answers assume each sort value ('no c', 'no s', etc.) occurs only one time. This solution will sort an array of any length, so long as each element has a sort property.

data.sort((obj1, obj2) => {
  const order = ['no s', 'no c', 'ready', 'pub'];
  const getOrder = (obj) => order.findIndex(item => item === obj.sort);
  return getOrder(obj1) - getOrder(obj2);
}

EDIT:

I made the function cleaner by removing a bulky switch statement and an unnecessary variable.

Note that you need to guarantee each sort value is valid for this solution, otherwise the object will be placed at the front of the array. If you want different behavior for invalid values, you can handle that in the getOrder function if you want invalid ones at the end, or if you want to filter them out altogether, you can just tack on a .filter(obj => order.includes(obj.sort)).

  • Related