Search products by startsWith in javascript 1

Search products by startsWith in javascript

const products = [
    "Dell hardcore 129 laptop",
    "iphone 1Tb camera flashlight phone",
    "yellow laptop with balack camera",
    "Dell 1x59 lenovo commercial yoga Laptop",
    "LG supernove laptop dell",
    "HTC low price phone",
    "Dell purple color phone with Laptop"
]
//Search start with 
const searching = "Dell";
const output = [];
for (const product of products) {
    if (product.toLowerCase().startsWith(searching.toLowerCase())) {
        output.push(product)
    }
}
console.log(output);
//Output:
// [
//     'Dell hardcore 129 laptop',
//     'Dell 1x59 lenovo commercial yoga Laptop',
//     'Dell purple color phone with Laptop'
// ]

Here is what the above code is Doing:
1. We have an array of products.
2. We have a variable called searching which contains the string we want to search for.
3. We have an empty array called output.
4. We loop through the products array.
5. We check if the product starts with the searching string.
6. If it does, we push it to the output array.
7. We print the output array.

Similar Posts