4 Different ways to filter an array

4 Different ways to filter an array

If you are new to the JavaScript world here are 4 different ways to filter data from an array.

  1. Using the filter() method - The filter() method creates a new array with all elements that pass the test implemented by the provided function. For example:

const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter(number => number % 2 === 0);
console.log(evenNumbers); // Output: [2, 4]        

2. Using the map() method - The map() method creates a new array with the results of calling a provided function on every element in the calling array. For example:

const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.map(number => number % 2 === 0 ? number : null).filter(Boolean);
console.log(evenNumbers); // Output: [2, 4]        

3. Using the reduce() method - The reduce() method applies a function against an accumulator and each element in the array to reduce it to a single value. For example:

const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.reduce((accumulator, number) => {
? if (number % 2 === 0) {
? ? return [...accumulator, number];
? } else {
? ? return accumulator;
? }
}, []);
console.log(evenNumbers); // Output: [2, 4]        

4. Using a for loop - A for loop can also be used to filter an array. For example:

const numbers = [1, 2, 3, 4, 5];
const evenNumbers = [];
for (let i = 0; i < numbers.length; i++) {
? if (numbers[i] % 2 === 0) {
? ? evenNumbers.push(numbers[i]);
? }
}
console.log(evenNumbers); // Output: [2, 4]        

要查看或添加评论,请登录

Sunil Soundarapandian的更多文章

  • Devin is Replacing Human Programmers?

    Devin is Replacing Human Programmers?

    In recent days, there has been a lot of buzz surrounding #Devin, the first AI software engineer from Cognition . As I…

    3 条评论
  • Have you ever wondered what is an “Event Loop”

    Have you ever wondered what is an “Event Loop”

    In most of the recent interviews this question is asked and if you wonder what an “Event loop” is, here is an answer…

    1 条评论
  • Top 3 static site generators

    Top 3 static site generators

    If you are a web developer or a content writer and looking for a slim and simple CMS without an overhead of deploying…

社区洞察

其他会员也浏览了