How to check all values of an array are equal or not in JavaScript ?
Given a javaScript array and the task is to print true if all the values of array are same using javaScript.
Approach 1:
- First get the array of elements.
- Pass it to an arrow function, which calls every() method on each array element and return true if each element matches with the first element of the array.
Example 1: This example uses array.every() method to print the desired response.
<!DOCTYPE HTML> < html > < head > < title > Check if all values of array are equal using JavaScript functions </ title > </ head > < body style = "text-align:center;" > < h1 style = "color:green;" > GeeksForGeeks </ h1 > < p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;" > </ p > < button onclick = "gfg_Run();" > click here </ button > < pre id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;" > </ pre > < script > var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var arr = [1, 1, 1, 1]; el_up.innerHTML = "Click on button to check if all values are" + " equal< br >< br >" + arr; const allEqual = arr => arr.every( v => v === arr[0] ); function gfg_Run() { el_down.innerHTML = allEqual(arr); } </ script > </ body > </ html > |
Output:
- Before clicking on the button:
- After clicking on the button:
Approach 2:
- First get the array of elements.
- Pass it to a function, which calls reduce() method on array element.
- Return true if each element matches with the first element of the array.
Example: This example uses array.reduce() method to print the false for the given array.
<!DOCTYPE HTML> < html > < head > < title > Check if all values of array are equal using JavaScript functions </ title > </ head > < body style = "text-align:center;" > < h1 style = "color:green;" > GeeksForGeeks </ h1 > < p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;" > </ p > < button onclick = "gfg_Run();" > click here </ button > < pre id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;" > </ pre > < script > var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var arr = ["GFG", "GFG", "GFG", "GfG"]; el_up.innerHTML = "Click on button to check if all" + " values are equal< br >< br >" + arr; function allEqual(arr) { if(!arr.length) return true; return arr.reduce(function(a, b) {return (a === b)?a:(!b);}) === arr[0]; } function gfg_Run() { el_down.innerHTML = allEqual(arr); } </ script > </ body > </ html > |
Output:
- Before clicking on the button:
- After clicking on the button: