37 lines
971 B
TypeScript
37 lines
971 B
TypeScript
import slugify from "./slugify";
|
|
|
|
export default function uniqueByKey<T extends { [k: string]: any } = any>(
|
|
arr: T[],
|
|
key: keyof T | (keyof T)[]
|
|
) {
|
|
let newArray = [] as T[];
|
|
let uniqueValues = [] as string[];
|
|
|
|
for (let i = 0; i < arr.length; i++) {
|
|
const item = arr[i];
|
|
|
|
let targetValue: string | undefined;
|
|
|
|
if (Array.isArray(key)) {
|
|
const targetVals: string[] = [];
|
|
|
|
for (let k = 0; k < key.length; k++) {
|
|
const ky = key[k];
|
|
const targetValuek = slugify(String(item[ky]));
|
|
targetVals.push(targetValuek);
|
|
}
|
|
targetValue = slugify(targetVals.join(","));
|
|
} else {
|
|
targetValue = slugify(String(item[key]));
|
|
}
|
|
|
|
if (!targetValue) continue;
|
|
|
|
if (uniqueValues.includes(targetValue)) continue;
|
|
newArray.push(item);
|
|
uniqueValues.push(targetValue);
|
|
}
|
|
|
|
return newArray;
|
|
}
|