Some, every and indexOf methods on arrays

Some, every and indexOf methods on arrays

Introduced in ES5, the only difference between Array.prototype.some() and Array.prototype.every() is the following:

  • some() is used to check if at least one of the elements of the array passes the test implemented by the provided function;
  • every() is used to check if all the elements of the array pass the test implemented by the provided function.

Check if at least one of the elements of the array meets the condition with some() method

The following example checks whether at least one element in the array is even or not:

// ES5+
function isEven(arr) {
    return arr.some(function (elem) {
        return elem % 2 === 0;
    });
}
const arr1 = [ 1, 3, 5, 2 ];
const arr2 = [ 1, 3, 5, 7 ];

console.log(isEven(arr1)); // output: true
console.log(isEven(arr2)); // output: false

If you're using ES6, you can use the arrow function with some() to make the syntax shorter, for example:

// ES6+
arr.some((elem) => elem % 2 === 0);

Check if all elements of the array meet the condition with every() method

The following example checks whether all elements in the array are even or not:

// ES5+
function allEven(arr) {
    return arr.every(function (elem) {
        return elem % 2 === 0;
    });
}
const arr1 = [ 2, 4, 6, 8 ];
const arr2 = [ 1, 2, 4, 6 ];

console.log(allEven(arr1)); // output: true
console.log(allEven(arr2)); // output: false

If you're using ES6, you can use the arrow function with every() to make the syntax shorter, for example:

// ES6+
arr.every((elem) => elem % 2 === 0);

Check for the presence of an element with indexOf() method

Since arrays can be changed, or mutated, at any time, there's no guarantee about where a particular piece of data will be on a given array, or if that element even still exists. Luckily, JavaScript provides us with another built-in method, indexOf(), that allows us to quickly and easily check for the presence of an element on an array. indexOf() takes an element as a parameter, and when called, it returns:

  • the index of that element, or
  • -1 if the element does not exist on the array.

For example:

let fruits = ['apples', 'pears', 'oranges', 'peaches', 'pears'];

fruits.indexOf('dates'); // => -1 meaning that the element is not present
fruits.indexOf('oranges'); // => 2
fruits.indexOf('pears'); // => 1

It is pretty much the same way to check for an element in a multi-dimensional array, except that we should loop into the nested array. For instance, the code below can be used to filter a nested array:

function filteredArray(arr, elem) {
  let newArr = [];
  for (let i = 0; i < arr.length; i++) {

    if (arr[i].indexOf(elem) != -1) {
      newArr.push(arr[i]); 
    }

  }
  return newArr;
}

console.log(filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3)); // => []
console.log(filteredArray([["trumpets", 2], ["flutes", 4], ["saxophones", 2]], 2)); // => ["flutes", 4]