/** * Extracts unique rows from data based on specified fields and sorts by up to two fields * @param data Array of data objects * @param fields Array of field names to use as a unique keys * @param sortFields Optional array of field names to sort by (up to two fields) * @returns Array of unique objects based on the specified fields, or an empty array if data is empty */ export function getUniqueRows>( data: T[], fields: (keyof T)[], sortFields?: (keyof T)[] ): T[] { const createCompositeKey = (item: T): string => { return fields.map((field) => String(item[field])).join("|"); }; const uniqueKeys = new Set(); const uniqueRows: T[] = []; data.forEach((item) => { const key = createCompositeKey(item); if (!uniqueKeys.has(key)) { uniqueKeys.add(key); uniqueRows.push(item); } }); if (sortFields && sortFields.length > 0) { uniqueRows.sort((a, b) => { for (let i = 0; i < sortFields.length; i++) { const field = sortFields[i]; if (a[field] < b[field]) return -1; if (a[field] > b[field]) return 1; } return 0; }); } return uniqueRows || []; }