As I learn more and more about JavaScript I realise that there is more and more that I don't know and I have realised that a great deal of what I am doing with JavaScript is examining data and doing stuff with that data. A great deal of that data is a list of things or an array.

In JavaScript there are methods, which are prebuilt bits of code for working with data, whether that data be:

  • Strings - words and numbers for example a person's name
  • Numbers - for example the cost of something
  • Boolean - true or false value for example an option is selected or not
  • Array - a list of things for example a list of peoples names.
  • Object - a complex bit of related data for example a person, their first/last names, age, date of birth, etc.

An array can be a list of strings, numbers, booleans, arrays, objects or a mixture of all of these.

Array.some()

This method allows you to check that a value appears in an array and will return true or false.

Here I have a simple array of numbers.

let simpleArray = [1, 2, 3, 4, 5, 6]
  

I can use the .some() method to check if a value appears in the array.

simpleArray.some(2)
// returns true as 2 is in the array
simpleArray.some(7)
// returns false as 7 is not in the array
  

If a value in an array is an object

Real life is usually a little more complex so let me explain why I am using this to give more context

Use Case

I have an id which I have got from the url:

https://mysite.com/user/abc123 id = abc123

I have an array of users, my data:

const users = [
  {
    id: "abc123",
    name: "Dave",
    age: 52
  },
  {
    id: "def456",
    name: "Tom",
    age: 36
  },
  {
    id: "ghi789",
    name: "Dick",
    age: 27
  }
]
  

Now I want to check to see if the id appears in the users array

Solution

users.some(user => user.id.includes(id))
  

This uses the .some() method and inside we have an arrow function that breaks each object in the array into a user.

Then it looks in that user for an id (or object key) and then uses the .includes() string method to see if the id I got from the url is in the current user object that is being inspected.

How I am using this

So I am checking to see if the user exists in my array and if it is I am loading that into the page, if not I make an API call to get the user.

if (users.some(user => user.id.includes(id))) {
  // load the user into the page
} else {
  // call function to get the user
  getUser(id);
  // load user into the page
}
  

Further reading

Other articles from the blog

  • A11y isn’t Just…

    Accessibility isn't just Screen Readers, Guidelines or for the disabled

    Date

  • Different types of programming quotes

    JavaScript Quotes

    In JavaScript there are a number of quote types that we can use: Single Quotes, Double Quotes and Backticks.