Created
June 11, 2024 03:13
-
-
Save alwaisy/14d51cff14e0fa453f1eee1ee9cd1b4a to your computer and use it in GitHub Desktop.
Combining Js string & array methods to develop search program
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Performs a case-insensitive search through an array of strings. | |
* | |
* @param {string[]} products - The array of strings to search through. | |
* @param {string} searchTerm - The term to search for (case-insensitive). | |
* @returns {string[]} An array containing the matching strings from the input array. | |
*/ | |
function caseInsensitiveSearch(products, searchTerm) { | |
// Convert everything to lowercase for case-insensitive comparison | |
const lowercaseProducts = products.map(product => product.toLowerCase()); | |
const lowercaseSearchTerm = searchTerm.toLowerCase(); | |
// Find matching products | |
const matchingProducts = lowercaseProducts.filter(product => product === lowercaseSearchTerm); | |
return matchingProducts; | |
} | |
// Example usage: | |
const products = ["Apple", "Banana", "Orange", "Grape"]; | |
const searchTerm = "apple"; | |
const matchingProducts = caseInsensitiveSearch(products, searchTerm); | |
console.log("Matching products:", matchingProducts); // Output: ["apple"] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Performs a case-insensitive search through an array of strings. | |
* | |
* @param products - The array of strings to search through. | |
* @param searchTerm - The term to search for (case-insensitive). | |
* @returns An array containing the matching strings from the input array. | |
*/ | |
function caseInsensitiveSearch(products: string[], searchTerm: string): string[] { | |
// Convert everything to lowercase for case-insensitive comparison | |
const lowercaseProducts = products.map(product => product.toLowerCase()); | |
const lowercaseSearchTerm = searchTerm.toLowerCase(); | |
// Find matching products | |
const matchingProducts = lowercaseProducts.filter(product => product === lowercaseSearchTerm); | |
return matchingProducts; | |
} | |
// Example usage: | |
const products: string[] = ["Apple", "Banana", "Orange", "Grape"]; | |
const searchTerm: string = "apple"; | |
const matchingProducts: string[] = caseInsensitiveSearch(products, searchTerm); | |
console.log("Matching products:", matchingProducts); // Output: ["apple"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment