Array Analysis

Arrays have built-in methods to analyse the contents of the array. Most of these methods take a function that returns true or false as an argument. Such a function is called a predicate.

The built-in methods are meant to be used instead of a for loop or the built-in forEach method:

Example of analysis using a for loop :

const numbers = [1, 'two', 3, 'four'];
for (var i = 0; i < numbers.length; i++) {
  if (numbers[i] === 'two') {
    return i;
  }
}
// => 1

Example of analysis using a built-in method:

const numbers = [1, 'two', 3, 'four'];
numbers.indexOf('two');
// => 1

Some other helpful built-in methods that are available to analyze an array are shown below. See MDN for a full list of array methods.

The indexOf() method returns the first index at which a given element can be found in the array, or 1-1 if it is not present.

const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];

console.log(beasts.indexOf('bison'));
// expected output: 1

// start from index 2
console.log(beasts.indexOf('bison', 2));
// expected output: 4

console.log(beasts.indexOf('giraffe'));
// expected output: -1

References

The includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate.

const numbers = [1, 'two', 3, 'four'];
numbers.includes(1);
// => true
numbers.includes('one');
// => false

References

The every() method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value. 2

const numbers = [1, 3, 5, 7, 9];
numbers.every((num) => num % 2 !== 0);
// => true

References

The some() method tests whether at least one element in the array passes the test implemented by the provided function. 3

const numbers = [1, 3, 5, 7, 9];
numbers.some((num) => num % 2 !== 0);
// => true

References

The find() method returns the value of the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned. 4

const numbers = [1, 3, 5, 7, 9];
numbers.find((num) => num < 5);
// => 1

References

The findIndex() method returns the index of the first element in the array that satisfies the provided testing function. Otherwise, it returns -1, indicating that no element passed the test. 5

const numbers = [1, 3, 5, 7, 9];
numbers.findIndex((num) => num > 7);
// => 4
numbers.findIndex((num) => num > 9);
// => -1

References


References