DEV Community

Rajnish Katharotiya
Rajnish Katharotiya

Posted on

function to check if all records are equal in array | javascript

Hey folks, welcome again in a new episode of series called Javascript Useful Snippets. Well, Javascript is one of the popular languages you can learn ( easily ). So, I’m going to share some shortcodes and useful javascript methods. These snippets can help you to make your development more efficient and faster. So, stay tuned till the end to learn something new…

Javascript Useful Snippets — allEqual()

In order to check whether every value of your records/array is equal to each other or not, you can use this function. allEqual() function returns true if the all records of a collection are equal and false otherwise. let’s look at the syntax…

const allEqual = arr => arr.every(val => val === arr[0]);

here, this function will get an array from parameter and in return, it’s using every ( method of the array ) to get individual records to compare it with the 0th index record. it’ll return true if all records are the same as the 0th index record or else false. Now, let’s look at the results…

Result 1:

const result = allEqual([ 3, 4, 5, 5, 5]) // output: false

Result 2:

const result = allEqual([ 5, 5, 5, 5, 5]) // output: true

As the first result shows, on 0th index record (3) won’t match to the first index record and it’ll return false from then only. while in case of the second result it’ll compare every record with 0th index record (5) where it’s equal to all record so the output is given as true.

Here one thing is notable is if we get a very first wrong match from that point further execution will be terminate and the result will be returned with a false value.

Thank you for watching/reading folks, if you found this informative and wanted to make me more content like this please support me on Patreon.

Now, Guys on the next episode I’m going to share a function to convert any string to capitalized in few seconds so you won’t need to do the manual process every time. so follow/subscribe to get notification…

Subscribe on youtube https://www.youtube.com/channel/UCvNjso_gPQIPacA6EraoZmg
Facebook: https://www.facebook.com/KatharotiyaRajnish/
Twitter: https://twitter.com/tutorial_spot

Top comments (4)

Collapse
 
francisco_diaz_3c67468c51 profile image
Francisco Diaz • Edited

With modern JavaScript you could do

const allEqual = (arr) => new Set(arr).size === 1;
Enter fullscreen mode Exit fullscreen mode

Since the a value in the set may only occur once; it is unique in the set's collection

Collapse
 
fernando_flores_9f076177e profile image
Fernando Flores

That is pretty good man!

Collapse
 
zaidrashid profile image
Zaid Rashid

Hey, this is nice. I was thinking of using map or reduce (check against average) but this solution is much simpler. Thanks for sharing.

Collapse
 
luciojpfilho profile image
Lúcio J. P. Filho 🇧🇷 🇺🇲 🇪🇸

if (Math.min(...array) === Math.max(...array)) {}