contains
The contains utility checks if a specific value exists within an array. Unlike the native Array.prototype.includes(), contains uses deep equality, making it suitable for finding objects and arrays within a list.
Implementation
View Source Code
ts
import { assert } from '../function/assert';
import { IS_ARRAY_ERROR_MSG, isArray } from '../typed/isArray';
import { isEqual } from '../typed/isEqual';
/**
* Checks if a value is present in an array.
*
* @example
* ```ts
* const arr = [1, 2, 3, { a: 1 }, 'hello'];
* const value = { a: 1 };
* contains(arr, value) // true;
* ```
*
* @param array - The array to check.
* @param value - The value to search for.
*
* @returns true if the value is present in the array, else false.
*
* @throws {TypeError} If the first argument is not an array.
*/
// biome-ignore lint/suspicious/noExplicitAny: -
export function contains<T>(array: T[], value: any): boolean {
assert(isArray(array), IS_ARRAY_ERROR_MSG, { args: { array }, type: TypeError });
return array.some((val) => isEqual(val, value));
}
contains.fp = true;Features
- Isomorphic: Works in both Browser and Node.js.
- Deep Equality: Correctly identifies objects, arrays, and nested structures.
- Type-safe: Properly typed for all input values.
API
ts
function contains<T>(array: T[], value: any): boolean;Parameters
array: The array to search.value: The value to search for. Uses deep comparison for complex types.
Returns
trueif the value is found in the array; otherwise,false.
Examples
Finding Primitives
ts
import { contains } from '@vielzeug/toolkit';
const numbers = [1, 2, 3, 4];
contains(numbers, 3); // true
contains(numbers, 9); // falseFinding Objects (Deep Equality)
ts
import { contains } from '@vielzeug/toolkit';
const users = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
];
// native includes() would return false here for a new object literal
contains(users, { id: 1, name: 'Alice' }); // trueFinding Nested Arrays
ts
import { contains } from '@vielzeug/toolkit';
const nested = [
[1, 2],
[3, 4],
];
contains(nested, [1, 2]); // trueImplementation Notes
- Throws
TypeErrorif the first argument is not an array. - Uses the
isEqualutility internally for comparisons. - For performance-critical code with very large arrays of primitives, consider using native
includes().