Filter all the items in an Array that match the condition in JavaScript

Let's filter all the authors that have written more than 10 blog posts,

const authors = [
  {
    name: 'Clarke',
    numberOfPosts: 11
  },
  {
    name: 'Bellamy Blake',
    numberOfPosts: 2
  },
  {
    name: 'Lexa',
    numberOfPosts: 6
  },
  {
    name: 'Octavia Blake',
    numberOfPosts: 10
  }
];

We will use the Array.filter method to filter the authors who has written more than 10 articles,

const filteredAuthors = authors.filter(author => {
  // return true will add it to the fitered list, return false will discard the item from the list
  return author.numberOfPosts >= 10;
});

console.log(filteredAuthors);

You can also achieve filtering using the Array.reduce method. Array.reduce is to do any kind of transformation in an Array. It is much more powerful than the Array.filter method. But for simple filtering, Array.filter method is enough.

If you want to learn about the Array.reduce method, you can check out our blog posts,