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

MrMuhammad
Giga Sage

Hi,

There are multiple ways to compare that. A quick way is to convert both the arrays to JSON string and then compare. 

Sample script. [Try below in background script for a quick look]

var a = [1, 2, 3, 5];
var b = [1, 2, 4, 5];
    
  // Comparing both arrays using stringify
  if(JSON.stringify(a)==JSON.stringify(b)){
      gs.info("same");
  } else {
      gs.info("Different");
  }

Regards,

Muhammad

Regards,
Muhammad

Hi Muhammad,

I'm only 1 array, not 2. If there were 2 arrays, this would be cake!

Good suggestion though

Oops I misread I believe. Please try Pranav's code below that will work!

Regards,
Muhammad

Anil Lande
Kilo Patron

Hi,

Do you want check check weather array has duplicate values?

Please check below link, you may find it helpful:

https://community.servicenow.com/community?id=community_question&sys_id=b336e0721b4cb4907a5933f2cd4b...

 

Thanks,

Anil Lande

Please appreciate the efforts of community contributors by marking appropriate response as correct answer and helpful, this may help other community users to follow correct solution in future.
Thanks
Anil Lande