Searching for Unique Javascript Array Values with Some

Ole Ersoy
Oct 2, 2022

--

Image by Monika Helmecke from Pixabay

Scenario

We have an array containing the values [1,2,3,4,5] . We want to find the unique value 3 and then stop looking.

Approach

We’ll be using some to iterate over the array. The some function stops iterating after the first match that is true , which in our case is 3 .

let arr: number[] = [1, 2, 3, 4, 5];var unique: number = NaN;function findThree(value: number) {
console.log(value);
unique = value;
return value == 3;
}
arr.some((v) => findThree(v));

We console log the value to see that we are only executing the loop 3 times.

Demo

--

--