sort by custom params

user_8454105 avatar
user_8454105
plain_text
02/29/2024 8:46 PM
1.2 KB
19
Indexable
    sortItemsByCustomOrder(items) {
      const order = ['company', 'pet', 'plans', 'contact', 'summary', 'ny'];
      return items.slice().sort((a, b) => {
        const keyA = Object.keys(a).find(key => order.some(prefix => key.startsWith(prefix)));
        const keyB = Object.keys(b).find(key => order.some(prefix => key.startsWith(prefix)));

        const priorityA = keyA ? order.findIndex(prefix => keyA.startsWith(prefix)) : order.length;
        const priorityB = keyB ? order.findIndex(prefix => keyB.startsWith(prefix)) : order.length;

        // Compare by priority, then by key alphabetically if the same priority
        if (priorityA !== priorityB) {
          return priorityA - priorityB;
        } else if (keyA && keyB) { // If both have keys, sort them alphabetically
          return keyA.localeCompare(keyB);
        } else {
          return 0; // Keep original order if no relevant keys
        }
      });
    }
Editor is loading...
Leave a Comment