Categories
JavaScript Answers

How to use the JavaScript array filter but only take first result?

Spread the love

Sometimes, we want to use the JavaScript array filter but only take first result.

In this article, we’ll look at how to use the JavaScript array filter but only take first result.

How to use the JavaScript array filter but only take first result?

To use the JavaScript array filter but only take first result, we can use the JavaScript array destructuring syntax.

For instance, we write:

const [first] = [7, 5, 3, 2, 1].filter(x => x % 2 === 0)
console.log(first)

to call filter with a callback that checks if the element is even to return an array of even numbers.

Then we use the destructuring syntax to get the first element from the returned array and assign it to first.

Therefore, first is 2 according to the console log.

Conclusion

To use the JavaScript array filter but only take first result, we can use the JavaScript array destructuring syntax.

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 *