datasquirel/package-shared/utils/delete-by-key.ts
Benjamin Toby 7e8bb37c09 Updates
2025-07-05 14:59:30 +01:00

38 lines
994 B
TypeScript

import _ from "lodash";
/**
* # Delete all matches in an Array
*/
export default function deleteByKey<T extends { [k: string]: any } = any>(
arr: T[],
key: keyof T | (keyof T)[]
) {
let newArray = _.cloneDeep(arr);
for (let i = 0; i < newArray.length; i++) {
const item = newArray[i];
if (Array.isArray(key)) {
const targetMatches: boolean[] = [];
for (let k = 0; k < key.length; k++) {
const ky = key[k];
const targetValue = item[ky];
const targetOriginValue = item[ky];
targetMatches.push(targetValue == targetOriginValue);
}
if (!targetMatches.find((mtch) => !mtch)) {
newArray.splice(i, 1);
}
} else {
let existingValue = newArray.find((v) => v[key] == item[key]);
if (existingValue) {
newArray.splice(i, 1);
}
}
}
return newArray;
}