1

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.

GG.
22k14 gold badges92 silver badges133 bronze badges
asked Apr 16, 2016 at 11:46
1
  • If the order of properties is always the same, you could use JSON.stringify. Commented Apr 16, 2016 at 12:22

1 Answer 1

2

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

answered Apr 16, 2016 at 12:00

2 Comments

Thanks. Awesome explanation.
I'm glad it helped! Happy Coding mate

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.