How to get array elements fulfilling a condition with JavaScript?

Sometimes, we want to get array elements fulfilling a condition with JavaScript.

In this article, we’ll look at how to get array elements fulfilling a condition with JavaScript.

How to get array elements fulfilling a condition with JavaScript?

To get array elements fulfilling a condition with JavaScript, we use the array filter method.

For instance, we write

const filterResult = [1, 16, 4, 6].filter((x) => {
  return x > 5;
});
console.log(filterResult);

to call [1, 16, 4, 6].filter with a function that checks if the item x being iterated through is bigger than 5.

If it’s bigger than 5, then it’ll be included in the returned array.

Conclusion

To get array elements fulfilling a condition with JavaScript, we use the array filter method.