Contact!

Find single or array of values in JavaScript array using includes

Multiple values in an Array, creating an inArray function in Javascript

I’ve looked at how to find the closest number in a JavaScript array, but what happens when you simply want to check whether a value (or an array of values) exist within that array? Would you like to be able to pass an array to Includes()?

This post will explore how you can find out whether a JavaScript array contains certain values using simple functions to evaluate to true or false. If you want to skip straight to the end there are some ready to go ‘inArray’ style JavaScript functions for you to use.

Look for a single value in an array using includes()

Includes() is a simple array function which returns true if the passed value matches a value within the array.

let haystack = ["12345", "hello", "world"];
let needle = "world";

let result = haystack.includes(needle);

console.log(result); // Output = true

The problem with includes() is that it requires a string value and therefore you can’t pass an array to it. To ‘pass an array’ to includes() we have to try a different approach.

Find an array of values using includes()

So includes() solves the problem of finding out whether a string exists within an array, but what happens if you want to match multiple string values? We could loop, map or filter the values to discover whether they exist, but the array prototype actually has a couple of very useful functions we can utilise.

Checking for a partial match using some()

The first of these is some(). This callback function will loop through an array until one of the conditions evaluates to true:

let haystack = ["12345", "hello", "world"];
let needle = ["world", "banana"];

let result = needle.some(i => haystack.includes(i));

console.log(result); // Output = true

Matching all values using every()

To query the array to match all of the values it is very similar. In this instance we replace some() with every() which evaluates true if all of the conditions are met.

let haystack = ["12345", "hello", "world"];
let needle = ["hello", "12345"];

let result = needle.every(i => haystack.includes(i));

console.log(result); // Output = true

Creating a reusable inArray function

Finally, we can put these approaches together into a reusable function:

function inArray(needle, haystack, matchAll = false) {
    if (matchAll) {
        return needle.every(i => haystack.includes(i));
    } else {
        return needle.some(i => haystack.includes(i));
    }
}

let result = inArray(needle, haystack, true);

Or if you like you could extend the array prototype. By doing this the function becomes available to all arrays. In this instance we are going to use the identifier ‘gb_’ to avoid possible code collisions from other libraries:

Array.prototype.gb_inArray = function(needle, matchAll = false) {
    if (matchAll) {
        return needle.every(i => this.includes(i));
    } else {
        return needle.some(i => this.includes(i));
    }
};

let result = haystack.gb_inArray(needle, true);
  1. Syed Atif Naeem says:

    This post of yours saved me from hours of work. I was really struggling to get an answer for matching using every.
    Thanks much.

  2. Tariq says:

    What do you think about the following approach!

    let hayStack = [“12345”, “hello”, “world”];
    let needle = [“hello”, “12345”];

    filterdData = hayStack.filter((item)=>{
    return (
    item.includes(‘hello’) &&
    item.includes(‘1213’)&&
    so on……..
    )
    })

    1. Tsabin Zebin says:

      Thanks mate!!

  3. Md Ishaq says:

    Hats off…brother.👏👏..big help..I just make a function for playing my wordle game by using your method.

  4. function toFindDuplicates() { says:

    make a functio

Join the discussion!

You might like:

Create, register and use shortcodes in WordPress

Create, register and use shortcodes in WordPress

by Gav 18/03/2023

Learn how to create and register your own WordPress shortcodes to add dynamic content to your posts and pages.

How to use guard clauses in JavaScript

How to/why use guard clauses in JavaScript

by Gav 16/03/2023

Learn how to improve code readability and performance by using guard clauses in JavaScript. Discover their benefits and best practices.

Implements and Extends, Object Oriented TypeScript

Implements and Extends, Object Oriented TypeScript

by Gav 15/03/2023

Learn the difference between implements and extends in TypeScript. Use Implements to implement interfaces and types, and extends to inherit from classes.

Reading/Parsing and Writing YAML files in PHP, Symfony

Reading/Parsing and Writing YAML files, PHP Symfony

by Gav 14/03/2023

In this tutorial we will look at using YAML in PHP. Learn about Parsing and Writing YAML files using Symfony's YAML component.

Measuring code execution performance in JavaScript

Measuring code execution performance in JavaScript

by Gav 13/03/2023

Measuring code execution performance is an important way to identify bottlenecks. Use these methods in JavaScript to help optimise your code.

Measuring script/code execution time in PHP using microtime

Measuring script/code execution time in PHP, microtime

by Gav 06/03/2023

Find bottlenecks, optimise and clean your code, and speed up your apps by measuring the execution time of your PHP scripts using microtime.

Regenerate WordPress media image sizes, programmatically

Regenerate WordPress media image sizes, programmatically

by Gav 25/02/2021

Learn how to regenerate and update WordPress media and image sizes both programmatically (without plugin), and also with a handy plugin.

Magic Constants in PHP. What they are and how to use them.

Magic Constants in PHP. What they are and how to use them

by Gav 15/02/2021

Ever seen constants like __DIR__ and __FILE__ being used in PHP? These are 'Magic Constants', and this is how we can use them.

Detecting Keypress JavaScript

Detect single and multiple keypress events: JavaScript

by Gav 16/10/2019

Learn how to use event listeners to detect and handle single and multiple keypress events in JavaScript. Add modifier keys to your application!