Join my Laravel for REST API's course on Udemy 👀

Filter JavaScript array by object property

August 20, 2022  ‐ 1 min read

In JavaScript we can filter arrays by object value using the .filter() method, which is available on array objects.

Lets for example assume that we have an array with the following options, and wish to filter based on the value of the required property.

const options = [
    name: 'a',
    required: true
    name: 'b',
    required: false

The .filter() method returns a new array instance, it doesn't mutate the array on which we call the function.

We can filter out the non-required options as follows.

const mandatory = options.filter(({required}) => {
  return required === true;

Or do the opposite and filter out the required options.

const optional = options.filter(({required}) => {
  return required === false;