filter items in an array of objects in javascript

To filter items in an array of objects in JavaScript, we can use the filter() method. The filter() method creates a new array with all elements that pass the test implemented by the provided function.

Let's assume we have an array of objects products with two properties name and price:

index.tsx
const products = [
  { name: 'apple', price: 0.5 },
  { name: 'banana', price: 0.2 },
  { name: 'pear', price: 0.8 }
];
120 chars
6 lines

To filter the array so that we only get the products with a price greater than or equal to 0.5, we can use the following code:

index.tsx
const expensiveProducts = products.filter(product => product.price >= 0.5);

console.log(expensiveProducts); // Output: [{ name: 'apple', price: 0.5 }, { name: 'pear', price: 0.8 }]
182 chars
4 lines

In this example, we passed an arrow function to the filter() method. This function takes a product object as an argument and returns true if the price property is greater than or equal to 0.5. The filter() method then creates a new array with only the products that pass this test.

Note that the filter() method doesn't modify the original products array. It returns a new array with the filtered items.

gistlibby LogSnag