Categories
JavaScript Answers

How to get array elements fulfilling a condition with JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *