search
Search objects in an array based on provided keys and query string. It only works with string and number values.
1. Code
/**
* Searches an array of objects based on a query string and specified keys.
*
* @template T - The type of objects in the array.
* @param {T[]} array - The array of objects to search.
* @param {string} queryString - The query string to search for.
* @param {(keyof T)[] | string[]} keys - The keys to search within each object.
* @returns {T[]} - The filtered array of objects that match the search criteria.
*/
const search = <T extends Record<string, unknown>>(
array: T[],
queryString: string,
keys: (keyof T)[] | string[]
): T[] => {
// Check if the query string or keys are empty, return empty array if true
try {
if (keys.length === 0) {
return []; // Return empty array if no keys are provided
}
if (!queryString.trim()) {
return array; // Return the original array if the query string is empty
}
// Loop through the array to filter objects
const filteredArray = array.filter((obj) => {
// Loop through the keys of each object
for (let key of keys) {
// Convert the value to string only for the comparison
let value = obj[key] as any;
if (typeof value !== "string" && typeof value !== "number") {
continue; // Skip the key if it is not a string or number
}
if (typeof value === "number") {
value = value.toString();
}
value = value.toLowerCase();
if (value.includes(queryString.toLowerCase()?.trim())) {
return true;
}
}
// Return false if none of the keys contain the query string
return false;
});
// Return the filtered array
return filteredArray;
} catch (error) {
return [];
}
};
export default search;
2. Installation
npx @jrtilak/lazykit@latest add search
3. Description
The search function is a utility function in JavaScript that performs a search operation on an array of objects based on a provided query string and keys. This function is particularly useful when you need to filter an array of objects based on certain criteria.
The function accepts three parameters: the original array to be searched, the query string, and an array of keys. The array should consist of objects, the query string is the value to be searched for, and the keys are the properties of the objects to be searched.
The function iterates over each object in the array, and for each object, it checks if any of the specified keys contain the query string. If a match is found, the object is included in the returned array. If no keys are provided, the function returns an empty array. If the query string is empty, the function returns the original array. This allows for flexible and powerful search functionality within your JavaScript applications.
4. Props
Prop
Type
Default Value
5. Examples
import search from ".";
const array = [
{ name: "John", age: 25 },
{ name: "Jane", age: 30 },
{ name: "John Doe", age: 35 },
];
// No keys provided
console.log(search(array, "John", []));
// Expected output: []
// Query string is empty
console.log(search(array, "", ["name"]));
// Expected output: [ { name: 'John', age: 25 }, { name: 'Jane', age: 30 }, { name: 'John Doe', age: 35 } ]
// Filtered array of objects matching the query
console.log(search(array, "John", ["name"]));
// Expected output: [ { name: 'John', age: 25 }, { name: 'John Doe', age: 35 } ]
// None of the keys contain the query string
console.log(search(array, "Doe", ["name"]));
// Expected output: []
// Keys does not exist in the object
console.log(search(array, "John", ["email"]));
// Expected output: []