乐闻世界logo
搜索文章和话题

Check if all values of array are equal

1个答案

1

Of course, to check if all values in an array are equal in JavaScript, we can use several different approaches. Below, I will detail two common methods with example code.

Method One: Using the every() Method

The every() method tests whether all elements in an array pass a specified test function. It returns a boolean value, returning true if all elements pass the test, and false otherwise. We can leverage this method to verify if all elements in the array are equal to the first element.

Example Code:

javascript
function allEqual(arr) { return arr.every(v => v === arr[0]); } // Example const arr1 = [1, 1, 1, 1]; const arr2 = [1, 2, 1, 1]; console.log(allEqual(arr1)); // Output: true console.log(allEqual(arr2)); // Output: false

Method Two: Using the Set Object

A Set is a special object type where each value must be unique. By converting the array to a Set and checking its size, we can determine if all values in the array are equal. If the Set size is 1, all values in the array are equal; if greater than 1, it indicates the presence of at least two distinct values.

Example Code:

javascript
function allEqualUsingSet(arr) { const uniqueValues = new Set(arr); return uniqueValues.size === 1; } // Example const arr3 = [3, 3, 3, 3]; const arr4 = [3, 3, 4, 3]; console.log(allEqualUsingSet(arr3)); // Output: true console.log(allEqualUsingSet(arr4)); // Output: false

Summary

Both methods have distinct advantages and disadvantages. The every() method offers more intuitive and readable code, while the Set method may perform better with very large arrays due to its internal optimizations for uniqueness handling. The choice depends on specific factors such as array size and expected data types. Typically, the every() method is widely adopted because of its straightforward nature.

2024年7月28日 19:05 回复

你的答案