Check if all Values in Array are Equal in JavaScript-Code Examples

Radu TM

Check if all Values in Array are Equal in JavaScript

JavaScript by Radu TM June 21, 2022

const checkAllValuesEqual = (arr) => {
  // check if array is empty
  if (arr.length === 0) return true;
  // compare first value in array to all other values
  for (let i = 1; i < arr.length; i++) {
    // if any value doesn't match, return false
    if (arr[i] !== arr[0]) return false;
  }
  // if we get to this point, all values must be equal
  return true;
};

console.log(checkAllValuesEqual([1, 2, 3, 4, 5, 6])); // false
console.log(checkAllValuesEqual([1, 1, 1, 1, 1, 1])); // true
console.log(checkAllValuesEqual([])); // true

0

20.506

Check if all Values in Array are Equal in JavaScript

JavaScript by Radu TM June 21, 2022

const checkValues = (arr) => {
  // check if all values in array are equal
  const firstValue = arr[0];
  for (let i = 1; i < arr.length; i++) {
    if (arr[i] !== firstValue) {
      return false; // not all values are equal
    }
  }
  return true; // all values are equal
};

0

20.506

Check if all Values in Array are Equal in JavaScript

JavaScript by Radu TM June 21, 2022

const values = [1, 2, 3, 4, 5];

// checks if all values are equal
const isEqual = values.every(value => value === values[0]);

console.log(isEqual); // false

0

20.506

Related JavaScript Queries

Latest JavaScript Queries

Explore code examples by categories