removeValues
Removes specific values from an array.
1/**
2 * Removes specific values from an array.
3 *
4 * @param arr - The input array.
5 * @param valuesToRemove - One or more values to be removed.
6 * @returns A new array without the specified values.
7 */
8export function removeValues<T>(arr: T[], ...valuesToRemove: T[]): T[] {
9 const toRemoveSet = new Set(valuesToRemove);
10 return arr.filter(item => !toRemoveSet.has(item));
11}Simple and intuitive API
Accepts one or more values to remove using rest parameters, making the function easy to use in a variety of scenarios.
Efficient lookup with
SetConverts
valuesToRemoveinto aSetfor constant-time lookups, ensuring optimal performance even with large input arrays.Non-mutating
Returns a new array, preserving the original input and adhering to functional programming best practices.
Supports multiple removals in one call
Convenient for batch exclusions (e.g., removing
[0, '', null]in one pass).Type-safe and generic
Works with any type of array (strings, numbers, objects, etc.), as long as the values can be compared using
===.
Tests | Examples
1test('removeValues removes specified primitives', () => {
2 expect(removeValues([1, 2, 3, 4, 2], 2, 4)).toEqual([1, 3]);
3 expect(removeValues(['a', 'b', 'c'], 'b')).toEqual(['a', 'c']);
4});
5
6test('removeValues removes falsy values if specified explicitly', () => {
7 expect(removeValues([0, 1, false, '', null], 0, false)).toEqual([1, '', null]);
8});
9
10test('removeValues handles empty input gracefully', () => {
11 expect(removeValues([], 1, 2)).toEqual([]);
12 expect(removeValues([1, 2, 3])).toEqual([1, 2, 3]);
13});Common Use Cases
Data cleanup
Remove known unwanted values such as
null,undefined,0,false, or empty strings from input data, especially before processing or displaying it.Filtering out reserved or invalid options
In form handling or UI selections, remove reserved values (e.g.,
"--Select--"or"N/A") from datasets.Array differencing
Use as a lightweight alternative to
difference()when you know the exact values to exclude.Custom list pruning
When dynamically filtering lists based on user preferences or permissions,
removeValuesprovides a quick exclusion mechanism.Removing banned words or items
Useful in content moderation, search filtering, or access control scenarios where certain items must be excluded.