DEV Community

avinash-repo
avinash-repo

Posted on

10 example of filter using in js

In JavaScript, filtering arrays is a common operation achieved using the filter() method. This method creates a new array with all elements that pass the test implemented by the provided function. Below are five basic examples demonstrating the usage of the filter() method:

  1. Filtering an array of numbers to include only even numbers:
const numbers = [1, 2, 3, 4, 5, 6];
const evenNumbers = numbers.filter(num => num % 2 === 0);
// Output: [2, 4, 6]
Enter fullscreen mode Exit fullscreen mode
  1. Filtering an array of strings to include only strings longer than a certain length:
const words = ["apple", "banana", "orange", "kiwi", "grape"];
const longWords = words.filter(word => word.length > 5);
// Output: ["banana", "orange"]
Enter fullscreen mode Exit fullscreen mode
  1. Filtering an array of objects based on a specific property value:
const products = [
  { name: "apple", price: 1.99 },
  { name: "banana", price: 0.99 },
  { name: "orange", price: 2.49 },
  { name: "kiwi", price: 3.29 }
];
const expensiveProducts = products.filter(product => product.price > 2);
// Output: [{ name: "orange", price: 2.49 }, { name: "kiwi", price: 3.29 }]
Enter fullscreen mode Exit fullscreen mode
  1. Filtering an array of objects based on multiple conditions:
const people = [
  { name: "John", age: 30, gender: "male" },
  { name: "Alice", age: 25, gender: "female" },
  { name: "Bob", age: 35, gender: "male" },
  { name: "Eve", age: 20, gender: "female" }
];
const malesUnder30 = people.filter(person => person.gender === "male" && person.age < 30);
// Output: [{ name: "John", age: 30, gender: "male" }]
Enter fullscreen mode Exit fullscreen mode
  1. Filtering an array of objects based on multiple criteria:
const data = [
  { name: 'John', age: 30, city: 'New York' },
  { name: 'Alice', age: 25, city: 'San Francisco' },
  { name: 'Bob', age: 35, city: 'New York' }
];

const filteredData = data.filter(item => {
  return item.age > 25 && item.city === 'New York';
});

console.log(filteredData);
// Output: [{ name: 'John', age: 30, city: 'New York' }, { name: 'Bob', age: 35, city: 'New York' }]
Enter fullscreen mode Exit fullscreen mode
  1. Filtering an array of strings based on a regular expression:
const words = ['apple', 'banana', 'grape', 'orange'];

const filteredWords = words.filter(word => /ap/.test(word));

console.log(filteredWords);
// Output: ['apple', 'grape']
Enter fullscreen mode Exit fullscreen mode
  1. Filtering an array of numbers to get prime numbers:
function isPrime(num) {
  for (let i = 2; i < num; i++) {
    if (num % i === 0) return false;
  }
  return num > 1;
}

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

const primeNumbers = numbers.filter(isPrime);

console.log(primeNumbers);
// Output: [2, 3, 5, 7]
Enter fullscreen mode Exit fullscreen mode
  1. Filtering an array of objects based on nested properties:
const users = [
  { name: 'Alice', address: { city: 'New York', country: 'USA' } },
  { name: 'Bob', address: { city: 'London', country: 'UK' } },
  { name: 'Charlie', address: { city: 'Paris', country: 'France' } }
];

const filteredUsers = users.filter(user => user.address.country === 'USA');

console.log(filteredUsers);
// Output: [{ name: 'Alice', address: { city: 'New York', country: 'USA' } }]
Enter fullscreen mode Exit fullscreen mode
  1. Filtering an array of objects based on an asynchronous condition:
const data = [
  { id: 1, status: 'pending' },
  { id: 2, status: 'approved' },
  { id: 3, status: 'rejected' }
];

async function isApproved(item) {
  // Simulating an asynchronous operation
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(item.status === 'approved');
    }, 1000);
  });
}

async function filterApproved(data) {
  const filteredData = await Promise.all(data.map(async item => {
    const approved = await isApproved(item);
    return approved ? item : null;
  }));
  return filteredData.filter(Boolean);
}

filterApproved(data).then(result => {
  console.log(result);
  // Output: [{ id: 2, status: 'approved' }]
});
Enter fullscreen mode Exit fullscreen mode

These examples demonstrate various scenarios where the filter() method in JavaScript is used to selectively extract elements from arrays based on specified conditions.

One of the most frequently asked interview questions regarding the filter() method in JavaScript often revolves around its practical usage and understanding of its functionality. Here's a common interview question along with its solution:

Interview Question:
Explain how you would use the filter() method to extract even numbers from an array of integers.

Solution:

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

const evenNumbers = numbers.filter(number => number % 2 === 0);

console.log(evenNumbers);
// Output: [2, 4, 6, 8, 10]
Enter fullscreen mode Exit fullscreen mode

Explanation:
In this solution:

  • We have an array of integers named numbers.
  • We utilize the filter() method on the numbers array to create a new array containing only even numbers.
  • Inside the filter() method, a callback function is provided, which is executed for each element in the array.
  • The callback function checks if the current element is even by using the modulo operator %. If the remainder after dividing the number by 2 is 0, it indicates an even number.
  • If the condition (number % 2 === 0) is true, the current element is included in the resulting array; otherwise, it is excluded.
  • Finally, the resulting array evenNumbers contains only the even numbers from the original numbers array.

This question assesses the candidate's understanding of array manipulation using the filter() method, as well as their ability to write concise and efficient code to solve a specific problem.

Certainly, another common interview question related to the filter() method in JavaScript might involve more complex scenarios or multiple conditions. Here's an example:

Interview Question:
Given an array of objects representing books, each with properties title, author, and year, write a function to filter out books published after the year 2000 and authored by female authors.

Solution:

const books = [
  { title: 'Book 1', author: 'John Doe', year: 1995 },
  { title: 'Book 2', author: 'Jane Smith', year: 2005 },
  { title: 'Book 3', author: 'Alice Johnson', year: 1999 },
  { title: 'Book 4', author: 'Emily Brown', year: 2003 }
];

function filterBooks(books) {
  return books.filter(book => {
    return book.year > 2000 && isFemaleAuthor(book.author);
  });
}

function isFemaleAuthor(author) {
  // Assuming a function to check if the author's name is female
  // This could be implemented using various methods like name databases or regular expressions
  return author.toLowerCase().includes('female');
}

const filteredBooks = filterBooks(books);
console.log(filteredBooks);
// Output: [{ title: 'Book 2', author: 'Jane Smith', year: 2005 }]
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • We have an array of book objects named books.
  • We define a function filterBooks() to filter out the books based on the given criteria.
  • Inside the filterBooks() function, we use the filter() method on the books array to create a new array containing only the books that meet the specified conditions.
  • The callback function provided to filter() checks two conditions:
    1. Whether the year property of the book object is greater than 2000.
    2. Whether the author's name indicates a female author, which is determined using the isFemaleAuthor() function.
  • The isFemaleAuthor() function checks if the author's name contains the word "female" (case-insensitive) to determine if the author is female.
  • Finally, the filtered array filteredBooks contains only the books that satisfy both conditions: published after the year 2000 and authored by female authors.

This question assesses the candidate's ability to combine multiple conditions within the filter() method and their problem-solving skills in real-world scenarios.

Certainly, here's a tricky question related to the filter() method in JavaScript:

Interview Question:
Given an array of strings, write a function to filter out strings that are anagrams of each other, keeping only one representative of each set of anagrams.

Solution:

function filterAnagrams(strings) {
  const map = new Map();

  strings.forEach(str => {
    const sortedStr = str.split('').sort().join('');
    map.set(sortedStr, str);
  });

  return Array.from(map.values());
}

const words = ['listen', 'silent', 'enlist', 'hello', 'world', 'hit', 'tih'];
const filteredWords = filterAnagrams(words);
console.log(filteredWords);
// Output: ['listen', 'hello', 'world', 'hit']
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • We define a function filterAnagrams() that takes an array of strings as input.
  • Inside the function, we initialize a Map to store the sorted version of each string as the key and the original string as the value.
  • We iterate over each string in the input array using forEach().
  • For each string, we sort its characters alphabetically, creating a canonical form of the word that will be the same for all anagrams.
  • We use this sorted string as the key in the Map and associate it with the original unsorted string.
  • After processing all strings, the Map will contain only one representative of each set of anagrams, as anagrams will have the same sorted representation.
  • Finally, we convert the values of the Map back into an array using Array.from() and return this array containing the filtered strings.

This question assesses the candidate's understanding of data structures, string manipulation, and their ability to devise an efficient algorithm for a specific problem using the filter() method in JavaScript.

Top comments (0)