Understanding the array methods Array.some() and Array.every() in JavaScript

There are lot of scenarios when we have an array of items and we need to check whether every item in that array satisfy a particular condition.

We might think that, why not use a for loop and flag to check this?

But there is an easier and much cleaner way to achieve this using Array.every().

Similarly, if we need to check if at least some items in an array satisfy a condition, we can use the Array.some() method.

Let us understand this better with some examples -

// We have a sample Array of persons from country ABC
const sampleArray = [
  {
    name: "John",
    occupation: "Doctor",
    age: 31,
    sex: "male",
    country: "ABC"
  },
  {
    name: "Jane",
    occupation: "Doctor",
    age: 26,
    sex: "female",
    country: "ABC"
  },
  {
    name: "Roger",
    occupation: "Engineer",
    age: 28,
    sex: "male",
    country: "ABC"
  },
  {
    name: "Riya",
    occupation: "Engineer",
    age: 32,
    sex: "female",
    country: "ABC"
  }
]

// I want to find out if all of them are from country "ABC"

const countryCheck = sampleArray.every(person => {
  return person.country === "ABC"
})
console.log("All are from the same country? ", countryCheck)

// I want to check if all are engineers
const engineerCheck = sampleArray.every(person => {
    return person.occupation === "Engineer"
})
console.log("All are Engineers? ", engineerCheck)

// I want to check if at least some women are engineers
const womenEngineers = sampleArray.some(person => {
    return person.occupation === "Engineer" && person.sex === "female"
})
console.log("Do we have at least some women engineers?", womenEngineers)

// I want to check if any of them are advocates
const lawyerCheck = sampleArray.some(person => {
return person.occupation === "Lawyer"
})
console.log("Do we have any lawyers?", lawyerCheck)

Output
image

Syntax of Array.every() and Array.some()

// Syntax
Array.every(callback)

const callback = (currentElement, index, array) => {
  // currentElement - current item in the array that we are iterating over over
  // index - index of the current item - optional
  // array - array that we are iterating over - optional
} 

// example usage
Array.every((currentElement) => {
    return currentElement > 1
})
// Syntax
Array.some(callback)

const callback = (currentElement, index, array) => {
  // currentElement - current item in the array that we are iterating over over
  // index - index of the current item - optional
  // array - array that we are iterating over - optional
} 

// example usage
Array.some((currentElement) => {
    return currentElement > 1
})

Hope you guys learned something new today. Keep coding!!

15