Skip to main content

Command Palette

Search for a command to run...

some() method explained : JS

Published
3 min read
some() method explained : JS
R

19, Hustler.

The some() method tests whether at least one of the elements in the array passes the test implemented by the provided function. The result of the some() method is a boolean. Let's see the syntax:-

const new = array.some(( v, i, a) => {
         // return boolean
   });

// newArray - the new array that is returned
// array - the array to run the map function on
// v - the current value being processed
// i - the current index of the value being processed
// a - the original array

The some() method can be thought of like a for loop, that is specifically for checking values. Let's see this example...

cost nums = [11, 12, 13, 14];
let aboveTwenty = false;
for(let i = 0; i < nums.length; i++) {
   if(!aboveTwenty) {
    aboveTwenty = nums[i] > 20;
   }
}
   // aboveTwenty = true;

This code results in a boolean, the result of the implemented. Yes, it works, but there is an easy to get this.

Now we will rewrite the previous function using the same() method.

const nums = [11, 22, 13, 14]; 
const aboveTwenty = nums.some(value => value > 20); 
      // allBelowTwenty = true;

Just see. No loop needed.

And using the arrow function we have a nice and clean function to create the same array. Because we only use the value, we only pass that to the some() method.

Let's peek to another example:

const nums = [11, 22, 13, 14]; 
const nums2 = [34, -1, 16, 75];

nums.some( value => vaue < 0 ); 
   // returns false

nums2.some( value => vaue < 0 ); 
  // returns true

The first statement returns false because not a single item in the nums array is smaller than 0.


I'm done! Read more;-

Thanks For Reading! Comment below if anything is going on your mind.

R

Thanks for sharing this 😀 usually the devs are so addicted in the filter or the map that generally they don't know about the existence of some and every; I like these two because they help to avoid the old for loop in various ways!

2
R
Rahul5y ago

Thank you very much.

1

More from this blog

R

RAHULISM - FrontEnd Web Developer

232 posts

18, Hustler.