diginext-utils
Version:
README.md
35 lines • 1.09 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.removeItemByKey = removeItemByKey;
/**
* Removes the first item from an array where the specified property matches the given value.
* Returns a new array without modifying the original.
*
* @template T - The type of elements in the array
* @param array - The array to remove from
* @param key - The property key to match
* @param value - The value to match
* @returns A new array with the matching item removed
*
* @example
* ```ts
* const users = [
* { id: 1, name: 'Alice' },
* { id: 2, name: 'Bob' },
* { id: 3, name: 'Charlie' }
* ];
* removeItemByKey(users, 'id', 2);
* // [{ id: 1, name: 'Alice' }, { id: 3, name: 'Charlie' }]
* ```
*/
function removeItemByKey(array, key, value) {
if (!Array.isArray(array)) {
return [];
}
const index = array.findIndex((item) => item[key] === value);
if (index === -1) {
return [...array];
}
return [...array.slice(0, index), ...array.slice(index + 1)];
}
//# sourceMappingURL=removeItemByKey.js.map