alexchenco alexchenco - 7 months ago 30
Javascript Question

Check if an array contains a specified object

The following function searches an object recursively through an object that has nested arrays:

function findDeep(arr, obj) {
console.log(arr)
if (arr.indexOf(obj) !== -1) {
console.log(arr)
return arr
} else {
arr.forEach(item => {
if (item.children) findDeep(item.children, obj)
})
}
}

const colors = {
children: [
{
name: 'white',
},
{
name: 'yellow',
children: [
{
name: 'black'
}
]
}
]
}

const color = {
name: 'black'
}

findDeep(colors.children, color)


The first
console.log(arr)
do log the matched array:

[
{ name: 'black' }
]


But he second
console.log(arr)
doesn't log anything. Shouldn't
arr.indexOf(obj)
return 1, and therefore make the second
console.log(arr)
log the array?

Here's the CodePen.

Answer

You can not find index of object in array using indexOf unless both the objects(passed in indexOf to test and present in array) are pointing to the same reference.

For example:

var a = {
  a: 10
};
var b = [{
  a: 10
}, {
  b: 20
}];
console.log(b.indexOf(a)); // Object `a` and Object in `0th` index of the array are having similar `key-values`
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>

But,

var a = {
  a: 10
};
var b = [a, {
  b: 20
}];
//`0th` index in the array is nothing but a variable holding `object`
console.log(b.indexOf(a)); //Same variable is tested in `indexOf`
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>

From the docs, indexOf() compares searchElement to elements of the Array using strict equality (the same method used by the === or triple-equals operator).

{} === {} will be evaluated as false because,

An expression comparing Objects is only true if the operands reference the same Object. If both operands are objects, then JavaScript compares internal references which are equal when operands refer to the same object in memory.[Ref]

There are few solutions and approaches but all of them will be doing iteration and comparing value of the key in object. Refer this answer