Here, in our example, we have an Array with several products that we will filter according to the user preference, in this case, price.
We need to interact on this set to find all the products that match our condition. There are four products within this array, and each one is an object.
We need to interact on the objects too, if you don’t know how to do it, just check this post on How to iterate an Object using loops and this one too where I teach 3 Powerful Ways to Access Properties in Javascript Objects.
So we gonna filter any item with price over $200, and it must be included within the new array.
const products = [
{ productName: "Television", price: "1000", shipping: "35" },
{ productName: "Pendrive", price: "200", shipping: "7" },
{ productName: "Camera", price: "450", shipping: "15" },
{ productName: "Mouse", price: "120", shipping: "5" }
];
const filtered = products.filter((item) => {
return item.price > 200;
});
console.log(filtered);
/*
[
{ productName: "Television", price: "1000", shipping: "35" },
{ productName: "Camera", price: "450", shipping: "15" }
]
*/
Just we like we did above, to filter the and array of objects based on multiples atributes you can still use the Javascript.filter()
method, the only difference will be in the callback function, which will need a little adjustment.
const products = [
{ productName: "Television", price: "1000", shipping: "35" },
{ productName: "Pendrive", price: "200", shipping: "7" },
{ productName: "Camera", price: "450", shipping: "15" },
{ productName: "Mouse", price: "120", shipping: "5" }
];
const filtered = products.filter((item) => {
return (item.price > 200 && item.shipping < 20);
});
console.log(filtered);
/*
[
{ productName: "Camera", price: "450", shipping: "15" }
]
*/
As a Newbie, I am continuously searching online for articles that can be of assistance to me. Thank you
Thank you for sharing excellent informations. Your web-site is so cool. I am impressed by the details that you¦ve on this web site. It reveals how nicely you perceive this subject. Bookmarked this web page, will come back for more articles. You, my pal, ROCK! I found just the info I already searched everywhere and simply couldn't come across. What a perfect website.
Leave a Reply