Jackson Tiu
Jackson Tiu

Reputation: 47

Is it possible to use .includes for an associative array/array of hashes?

I have a following array that needs to use .includes to check if their is an object that has duplicate or none. The problem is it always returns false so I'm not sure if there is a correct way or .includes can't be used this way.

var array_rooms = [{
    type: "Heritage",
    n: 1
  }, {
    type: "Hanuono",
    n: 1
  }, {
    type: "Bangon",
    n: 1
  }, {
    type: "Heritage",
    n: 1
  }]
console.log(array_rooms.includes("Heritage"));
//should return true

Upvotes: 2

Views: 2374

Answers (1)

31piy
31piy

Reputation: 23869

includes is well-suited to search for primitives. You should use some to check for inner properties of objects:

var rooms = [{
  type: "Heritage",
  n: 1
}, {
  type: "Hanuono",
  n: 1
}, {
  type: "Bangon",
  n: 1
}, {
  type: "Heritage",
  n: 1
}]

console.log(rooms.some(item => item.type === "Heritage"));

Upvotes: 6

Related Questions