sort by custom params

 avatar
user_8454105
plain_text
7 months ago
956 B
1
Indexable
Never
    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
        }
      });
    }
Leave a Comment