loading...
Cover image for Quick JavaScript Tip: the some() method

Quick JavaScript Tip: the some() method

mattsparks profile image Matt Sparks ・2 min read

I recently learned of a great JavaScript method I'd never used. It was brought to my attention by Wes Bos. The some() method is a convenient way to test the values of an array and see if at least one value returns true. some() was implemented before ES6 and its support is wide-spread (Internet Explorer 11 supports it).

It's important to note that this method only works on true Arrays. Other iterable types do not implement this method.

Problem: You have an array containing the types of animals your hotel allows. How can you determine if your pet snake, Mr. Slithers, can come along on your trip?

An Older Way:

var animals = ['dogs', 'cats', 'snakes', 'birds', 'pandas'];
var snakesAllowed = false;

for (var i = 0; i < animals.length; i++) {
  if(animals[i] === 'snakes') {
    snakesAllowed = true;
    break;
  }
}

console.log(snakesAllowed); // true

Using .some():

// Using arrow functions
const animals = ['dogs', 'cats', 'snakes', 'birds', 'pandas'];

const snakesAllowed = animals.some((type) => type === 'snakes');

console.log(snakesAllowed); // true

// Using normal functions
const animals = ['dogs', 'cats', 'snakes', 'birds', 'pandas'];

const snakesAllowed = animals.some(function(type) {
  return type === 'snakes';
});

console.log(snakesAllowed); // true

Addendum:

@attacomsian mentioned in the comments that .includes() would be a better fit for the problem above. I completely agree. The example above was just to illustrate how .some() works rather than solve the problem in the most efficient way.

For another example to illustrate .some()'s functionality, let's say we have an array of comic book prices and we want to know if any cost more than $10.

const prices = [5, 8, 11, 10, 25];
const aboveTen = prices.some((price) => price > 10);

console.log(aboveTen); // true

Further reading: MDN web docs

Posted on by:

mattsparks profile

Matt Sparks

@mattsparks

I've been a web developer for a bit. I enjoy donuts and horror movies.

Discussion

markdown guide
 

I think .includes() is better than .some() for checking if an array contains a value or not:

const animals = ['dogs', 'cats', 'snakes', 'birds', 'pandas'];
animals.includes('snakes'); // true

.some() is good for other use-cases like finding if a value > 15 exists in an array:

[2, 15, 18, 5, 4].some(x => x > 15);  // true
 

I agree, .includes() would be a better solution for the specific problem I laid out. I just wanted to give a simple bit of code to illustrate how .some() works.

I'll try and add a second example to show another use-case.

Thanks!

 

I was thinking the same string, but some reminds me of a function I wrote a long time ago (in PHP) called someValidStrings which checked an array to make sure that there was at least 1 value that was correctly typed as a String, and also fulfilled some other business logic on what was considered "valid" (think: string length, ends with a run of 3 numbers, etc.). This is a case that some would excel at with the function callback rather than just looking for a certain value.

I was thinking that I could use find for the same purpose, but I see that there's a logical benefit to returning a boolean directly rather than a value that would have to be checked. I imagine find, some and findIndex work very similarly and only really differ in what they return.

 

It is quite handy!

I used .some() coupled with .includes() a while back to cross-reference two string arrays to make sure the user had at least one of the required roles for an action. The benefit of .some() here is that it will return true no matter how many of the iterations are false, as long as one of them is true.

//sample data
let userRoles = ['a','b','c','d'];
let validRoles = ['c','d','e','f'];
//end sample data

private isRoleValid(userRoles: string[], validRoles: string[]) {
    return userRoles && userRoles.some(e => validRoles.includes(e));
}
 

Nice post!

A strange example 😅:

// check for types! in this case, check if your array has a number
["str", "str2", {key: 3}, 5].some(x => typeof x === "number"); // true
["str", "str2", {key: 3}, "5"].some(x => typeof x === "number"); // false
 

can't we use simply animals.indexOf("snakes") > -1

 
 

You can! That's the beauty of code, there's usually more than one way to solve a problem. It all comes down to preference and the task at hand.

 

Reminds me of LINQ, very useful to have this in JS. Thanks for the post.

 

Nice post Matt and very useful!

Thank you!

P.S. I also use .includes() but careful, ie doesn't support it.

 

Amazing, thank you for sharing

 

This could also be accomplished with filter and then calling length, right?

 
 

This could be very useful ! Never ever heard of this function or used it! Seems really nice together with the arrow function syntax! Thank you!!

 

Interesting. I can see some immediate uses now for my rss project. Thank you