55

I'm looking for a good way to check if an object exist in an array of objects. The intended result is true when all keys/values are present in the same object in that array.

The answers I found by browsing stackoverflow like Find object by id in an array of JavaScript objects which is using jQuery.grep or Find a value in an array of objects in Javascript return the found object. What I'm looking for is a boolean result (not the found object).

I know that I can loop for all array elements and then compare each value....etc

But what I mean is if there is a way to use JS methods like this:

var listOfObjecs = [
 {id: 1, name: "Name 1", score: 11},
 {id: 2, name: "Name 2", score: 22},
 {id: 3, name: "Name 3", score: 33},
 {id: 4, name: "Name 4", score: 44},
 {id: 5, name: "Name 5", score: 55},
];

var isObjectExist = function(search){
  return listOfObjecs.filter(function(obj){
     if(obj.id===search.id && obj.name===search.name && obj.score===search.score){
          return true;
     }
     return false;
  });
}

console.log( isObjectExist({id: 3, name: "Name 3", score: 33}) );
//outputs the found object [{id: 3, name: "Name 3", score: 33}]

console.log( isObjectExist({id: 9, name: "Name 3", score: 33}) );
//outputs an empty object []

This is because:

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

If there is no native JavaScript method (returning true or false) how can update the isObjectExist() function to return true or false?

Community
  • 1
  • 1
Ala Eddine JEBALI
  • 7,033
  • 6
  • 46
  • 65
  • 7
    [`Array.prototype.some()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some) – Pointy Jan 30 '17 at 19:28
  • 2
    What about `!!arr.find(function(){...});` See [`Array.find()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find) – zero298 Jan 30 '17 at 19:29
  • @zero298 The find() method returns a value of the first element in the array that satisfies the provided testing function. Otherwise undefined is returned. So **no boolean result**. – Ala Eddine JEBALI Jan 30 '17 at 19:30
  • Possible duplicate of [How do I check if an array includes an object in JavaScript?](http://stackoverflow.com/questions/237104/how-do-i-check-if-an-array-includes-an-object-in-javascript) – Heretic Monkey Jan 30 '17 at 19:31
  • That's why you add `!!` to the return. This casts truthy (an object) to `true` and falsy (undefined) to `false`. – zero298 Jan 30 '17 at 19:31
  • 2
    @zero298 wrong function for the job, will fail if the entity being sought has a falsey value. – Alnitak Jan 30 '17 at 19:33
  • 2
    I recommend reading through the documentation for arrays to see all the functions, because there really aren't that many, and it will save you lots of time in the future. – 4castle Jan 30 '17 at 19:44

6 Answers6

104

The Array.prototype.some method:

The some() method checks if any of the elements in an array pass a test (provided as a function). The some() method executes the function once for each element present in the array: If it finds an array element where the function returns a true value, some() returns true (and does not check the remaining values)

Alnitak
  • 334,560
  • 70
  • 407
  • 495
Matt Spinks
  • 6,380
  • 3
  • 28
  • 47
8

This works for me:

const findInArray = (myArray, item) => {
 !!myArray.find((el) => el == item)
};

Update, even easier:

 ['cat', 'dog', 'bat'].includes('dog');  
aarkerio
  • 2,183
  • 2
  • 20
  • 34
7

I'm sharing an example based on comments above, it may help others:

  const listOfObjecs = [
    { id: 1, name: "Name 1", score: 11 },
    { id: 3, name: "Name 3", score: 33 },
    { id: 2, name: "Name 2", score: 22 },
    { id: 3, name: "Name 3", score: 33 },
    { id: 4, name: "Name 4", score: 44 },
    { id: 5, name: "Name 5", score: 55 },
    { id: 3, name: "Name 3", score: 33 },
  ];
  const search1 = { id: 3, name: "Name 3", score: 33 };
  const search2 = { id: 9, name: "Name 3", score: 33 };

  // Using Array.prototype.some()
  const resSomeSearch1 = listOfObjecs.some(item => JSON.stringify(item) === JSON.stringify(search1));
  console.log(`resSome(search1): ${resSomeSearch1}`); // outputs: true
  const resSomeSearch2 = listOfObjecs.some(item => JSON.stringify(item) === JSON.stringify(search2));
  console.log(`resSome(search2): ${resSomeSearch2}`); // outputs: false

  // Using Array.prototype.filter()
  const resFilterSearch1 = !!listOfObjecs.filter(item => JSON.stringify(item) === JSON.stringify(search1)).length;
  console.log(`resFilter(search1): ${resFilterSearch1}`); // outputs: true
  const resFilterSearch2 = !!listOfObjecs.filter(item => JSON.stringify(item) === JSON.stringify(search2)).length;
  console.log(`resFilter(search2): ${resFilterSearch2}`); // outputs: false

  // Using Array.prototype.find()
  const resFindSearch1 = !!listOfObjecs.find(item => JSON.stringify(item) === JSON.stringify(search1));
  console.log(`resFind(search1): ${resFindSearch1}`); // outputs: true
  const resFindSearch2 = !!listOfObjecs.find(item => JSON.stringify(item) === JSON.stringify(search2));
  console.log(`resFind(search2): ${resFindSearch2}`); // outputs: false
Ala Eddine JEBALI
  • 7,033
  • 6
  • 46
  • 65
3

The find() method returns a value of the first element in the array that satisfies the provided testing function. Otherwise undefined is returned. So no boolean result.

@AlaDejbali's comment on his post.

Let's take this array :

var arr = [{
        name: "Ala",
        age: 20,
    },
    {
        name: "Jhon",
        age: 22,
    },
    {
        name: "Melissa",
        age: 12,
    },
];

Of course, find() returns the whole object inside your array but that depends on your implemented function inside find for example :

function findObject(arr, value) {
    if (Array.isArray(arr)) {
        return arr.find((value) => {
            return value.age === 20;
        });
    }
}

When we call this function like this :

console.log(findObject(arr, 20));

The resul will be :

{name: "Ala", age: 20}

And as far as we know undefined is not an object so we can test the returned result :

function findObject(arr, value) {
    const element = arr.find((value) => {
        return value.age === 20;
    });
    return typeof element === "object" ? true : false;
}

Or in other way :

function findObject(arr, value) {
        const element = arr.find((value) => {
            return value.age === 20;
        });
        return typeof element === "undefined" ? false : true;
    }
0

return boolean value if an object exists in array of objects.

var listOfObjecs = [
  { id: 1, name: "Name 1", score: 11 },
  { id: 2, name: "Name 2", score: 22 },
  { id: 3, name: "Name 3", score: 33 },
  { id: 4, name: "Name 4", score: 44 },
  { id: 5, name: "Name 5", score: 55 },
];

var object = { id: 3, name: "Name 3", score: 33 };
var booleanValue = listOfObjecs.filter((item) => 
                   item.id === object.id && 
                   item.name === object.name && 
                   item.score === object.score).length > 0
console.log({booleanValue})
0

This is a snippet that complements the answer provided by @MattSpinks

A basic example using the some() JS method

const ids = [1,2,3,4,5]

console.log(
  ids.some(id => id == 1) // true
)

console.log(
  ids.some(id => id == 0) // false
)
Gass
  • 7,536
  • 3
  • 37
  • 41