Wednesday, August 11, 2021

How search product from an array with name using javascript

 

Search a product name from an array using javascript code 



var products = [

    { name: 'Samsung Smart Phone', price: 15000 },
    { name: 'Walton Smart S7', price: 12000 },
    { name: 'Oppo Smart V5', price: 14000 },
    { name: 'LG Smart LG', price: 18000 },
    { name: 'Sony erricson', price: 20000 },
    { name: 'Samsung Smart Phone', price: 16000 },
    { name: 'Samsung 55 Phone', price: 19000 },
    { name: 'Asus f23 Phone', price: 16000 },
]

function searchProducts(products, searchtext) {
    const matched = [];
    for (const product of products) {
        const getname = product.name;
        if (getname.indexOf(searchtext) != -1) {
            matched.push(getname);
        }
    }
    return matched;


}

const getItems = searchProducts(products, 'Phone');
console.log(getItems);

No comments:

Post a Comment