OrderByITEMKEY

 avatar
user_8454105
plain_text
2 months ago
809 B
2
Indexable
Never
// Method to reorder items based on the key prefix
const reorderItems = (array) => {
  const order = ['company', 'pet', 'plans', 'contact', 'summary', 'ny'];
  
  return array.sort((a, b) => {
    const rankA = order.findIndex(prefix => a.key.startsWith(prefix));
    const rankB = order.findIndex(prefix => b.key.startsWith(prefix));
    
    // If both keys have defined ranks, compare them
    if (rankA !== -1 && rankB !== -1) {
      return rankA - rankB;
    }
    
    // If one key does not have a defined rank, it should come after
    if (rankA === -1 && rankB !== -1) {
      return 1;
    }
    if (rankB === -1 && rankA !== -1) {
      return -1;
    }
    
    // If neither key has a defined rank, they are considered equal in terms of sorting
    return 0;
  });
};
Leave a Comment