how to check if an array includes an object in javascript code example

Example 1: check if object is present in array javascript

//Use something like this:

function containsObject(obj, list) {
    var i;
    for (i = 0; i < list.length; i++) {
        if (list[i] === obj) {
            return true;
        }
    }

    return false;
}

//In this case, containsObject(car4, carBrands) is true. Remove the carBrands.push(car4); call and it will return false instead. If you later expand to using objects to store these other car objects instead of using arrays, you could use something like this instead:

function containsObject(obj, list) {
    var x;
    for (x in list) {
        if (list.hasOwnProperty(x) && list[x] === obj) {
            return true;
        }
    }

    return false;
}

Example 2: how to Check if an array contains an object in javascript

// To check if an array contains an Object

const myArrayObj = [{
    'username': 'Player 1',
    'email': '[email protected]'
}, {
    'username': 'Player 2',
    'email': '[email protected]'
}];

// Create a helper function to compear the objects
const isEqual = (first, second) => {
    return JSON.stringify(first) === JSON.stringify(second);
}

const result = myArrayObj.some(e => isEqual(e, {
    'username': 'Player 1',
    'email': '[email protected]'
}));

console.log(result); // true

Example 3: check object in array javascript

var obj = {a: 5};
var array = [obj, "string", 5]; // Must be same object
array.indexOf(obj) !== -1 // True

Example 4: javascript array contains object

// Works in all browsers
if (array.index(object) !== -1) {
  console.log(`my object is in my array`)
}

// ES7 :
if(array.includes(oject)) {
  console.log(`my object is in my array`)
}

Example 5: check if property has value in array javascript

const magenicVendorExists =  vendors.reduce((accumulator, vendor) => (accumulator||vendor.Name === "Magenic"), false);