Javascript
Filter

Practical example to filter desired data

Example 1 - Basic: filter by word size

const words = ['spray', 'elite', 'exuberant', 'destruction', 'present'];
 
const result = words.filter((word) => word.length > 6);

Example 2 - Basic: Word starting with letter

const words = ['spray', 'perfct', 'elite', 'persistence', 'exuberant', 'destruction', 'present', 'possible'];
 
const result = words.filter((word) => word[0] === "p");

Example 3 - Basic: Last letter of the string

const words = ['spray', 'perfct', 'elite', 'persistence', 'exuberant', 'destruction', 'present', 'possible'];
 
const result = words.filter((word) => word.slice(-1) === "t"); // Slice from end
 
// const result = words.filter((word) => word.charAt(word.length - 1) === "t"); // or get the charCodeAt last position

Example 4 - Intermediate:

const products = [
  { id: 1, name: "Laptop", price: 1200, available: true },
  { id: 2, name: "Phone", price: 800, available: false },
  { id: 3, name: "Tablet", price: 500, available: false },
  { id: 4, name: "Headphones", price: 150, available: true },
];
 
const filterProducts = (products, minPrice, maxPrice) => {
  return products.filter((product) => product.available && product.price >= minPrice && product.price <= maxPrice);
};
Last updated on