How to check if values in array are equal

matthew_magee1
Giga Guru

Hello all,

I've got an array that I'm building through a GlideRecord query.

I want to see if all the values match.

For example, here is the array: [a,a,a,a,b]

Here is some javascript I found online:

var array1 =  [a,a,a,a,b];

var check = array1.every( (val, i, arr) => val === arr[0] );

gs.info(check);

In the example above, the expected result would be 'false'.


However, when I run the above, I get Javascript compiler errors (line 2 specifically).

I'm sure there's another way to do this check, just not sure how.

Any help is greatly appreciated-

 

 

1 ACCEPTED SOLUTION

Pranav Bhagat
Kilo Sage

 
You can't use every as it is ES6 format, ES5 is support in servicenow, try this 

function identical(array) {
    for(var i = 0; i < array.length - 1; i++) {
        if(array[i] !== array[i+1]) {
            return false;
        }
    }
    return true;
}


Background script code

 

function identical(array) {
    for(var i = 0; i < array.length - 1; i++) {
        if(array[i] !== array[i+1]) {
            return false;
        }
    }
    return true;
}

var a = [a,a,a,a]

gs.print(identical(a));

View solution in original post

11 REPLIES 11

Perfect!

Never would have figured this out on my own. 

Big Thumbs Up!

Drew Carpenter
Tera Expert

** Outdated thread **
this script does work as long as your array is formatted properly.

var arr = ["a", "b"];
var check = arr.every((val, i, arr) => val === arr[0]);
gs.info(check);
*** Script: false

var arr = ["a""a"];
//var arr = [1,1,1,1,1,1,1,1];
var check = arr.every((val, i, arr) => val === arr[0]);
gs.info(check);
*** Script: true