February 25, 2020
ArraySome and ArrayEvery added in 2018 update 5
Comments
(0)
February 25, 2020
ArraySome and ArrayEvery added in 2018 update 5
I try to bend the internet to my will.
Wizard 34 posts
Followers: 23 people
(0)

I’d missed (or forgotten) that `ArraySome` and `ArrayEvery` were added in ColdFusion 2018 update 5 so thought I’d blog about it in case others weren’t aware.

Now we know they exist, what are they for?

ArraySome

ArraySome will return true if any of the elements in the array meet a specific condition. Here’s a simple example:

a = [10, 12, 14, -14, -12, -10];
hasNegativeNumber = ArraySome(a, function(el) {
  return el < 0;
});

In the above example hasNegativeNumber will be true as there is a negative number in the array.

For those of you who like using concise code we can write the above as:

a = [10, 12, 14, -14, -12, -10];
hasNegativeNumber = a.some((el) => el < 0);

Running the above gives exactly the same result.

We can also use ArraySome with more complex data. For example:

a = [
  {age: 10}, {age:16}, {age:18}, {age:20}
];
hasAdult = a.some((el) => el.age >= 18);

ArrayEvery

ArrayEvery¬†will return true if all of the elements in the array meet a specific condition. Here’s a simple example:

a = [10, 12, 14, -14, -12, -10];
allPositive = ArrayEvery(a, function(el) {
  return el >= 0;
});

In the above example `allPositive` will be false as there are negative numbers in the array.

As before we can also use it on more complex data:

a = [
  {age: 10}, {age: 14}, {age:18}, {age:20}
];
allChildren = a.every((el) => el.age < 18);

In the above example allChildren will be false.

The inquisitive among you are probably wondering if these functions exit immediately when the condition fails. I wondered the same. We can test that and use the 2nd parameter passed into the callback which is the current index.

a = [10, 12, -12, -10];
allPositive = a.every((el, i) => {
  writeoutput("#i#: #el#<br>");
  return el >= 0;
});
writeoutput("allPositive: #allPositive#<br>");

Running the above code outputs:

1: 10
2: 12
3: -12
allPositive: NO

So as you can see, when it finds a condition that does not pass it exits. Just for good measure here’s a similar test for ArraySome.

a = [10, 12, -12, -10];
hasNegative = a.some((el, i) => {
  writeoutput("#i#: #el#<br>");
  return el < 0;
});
writeoutput("hasNegative: #hasNegative#<br>");

The output from that is:

1: 10
2: 12
3: -12
hasNegative: YES

You can run the code samples:
run the code samples on cffiddle

0 Comments
Add Comment