Javascript – Check if an array contains one or more items from another array.

While there are other interesting ways to achieve this such as arrow functions, I’ve decided to share with you a simple yet effective way that is supported in all major browsers. Refer to code and usage below:

/**
 * @description determine if an array contains one or more items from another array.
 * @param {array} haystack the array to search.
 * @param {array} arr the array providing items to check for in the haystack.
 * @return {boolean} true|false if haystack contains at least one item from arr.
 */
function check_arrayA_items_exists_in_arrayB(haystack, arr) {
    return arr.some(function (v) {
        return haystack.indexOf(v) >= 0;
    });
}

 

Usage:

var userProducts = {
	action: "getProducts",
	products: ["978","970", "979", "980", "981"]
}
var globalProducts= ["978","970"];

if(check_arrayA_items_exists_in_arrayB(userProducts.products, globalProducts)){
	console.log('item/s exists');
}


Do you need help with a project? or have a new project in mind that you need help with?

Contact Me