Check if all or some array elements pass a condition in JavaScript

Introducing every method

if you want to check if all elements in the array are passing a condition you can use every method. every accepts a callback which should return a boolean to indicate a pass or a fail.

const todos = [
  {
    id: 1,
    label: "Todo 1",
    is_completed: true
  },
  {
    id: 2,
    label: "Todo 2",
    is_completed: true
  },
  {
    id: 3,
    label: "Todo 3",
    is_completed: true
  }
];

// returns true because all todos are completed
todos.every((todo) => todo.is_completed);

every returns true if all elements are passing a condition. Otherwise it returns false.

const todos = [
  {
    id: 1,
    label: "Todo 1",
    is_completed: true
  },
  {
    id: 2,
    label: "Todo 2",
    is_completed: false
  },
  {
    id: 3,
    label: "Todo 3",
    is_completed: true
  }
];

// returns false because not all todos are completed
todos.every((todo) => todo.is_completed);

Exploring some method

Another similar method is some which iterates through the array and accepts a callback. It returns true if at least one element is passing a condition.

const todos = [
  {
    id: 1,
    label: "Todo 1",
    is_completed: false
  },
  {
    id: 2,
    label: "Todo 2",
    is_completed: false
  },
  {
    id: 3,
    label: "Todo 3",
    is_completed: true
  }
];

// returns true because at least one todo is completed
todos.some((todo) => todo.is_completed);

Ivan Bernatović

I am a full-stack engineer who likes to program, architect and read.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.