Algorithm : Deep object Comparison using DFS(Depth first search)

Saransh Khobragade
2 min readMar 10, 2020

--

So i created a basic algorithm in javascript for object comparison for any depth possible although you can use JSON.stringyfy() method but it is costly and not efficient also.

This algorithms tells which keys are missing, if type mismatch is there for keys it also brings back trace path of mismatch of type also.

Please go through below code.

So its gives output like :

[ { source_trace: [ 'nested', 0 ],
source: [ 4.5 ],
target: 4.5,
index: 'a' },
{ source_trace: [ 'nested', 0, 'v', 0 ],
source: 23,
target: 'a',
index: 'age' } ]

Basically we are comparing two objects a_obj and b_obj and giving as input to these function and function returns these output array of 2 objects means there are 2 issues or mismatch.

source_trace : it gives the trace of issue happened so at key ‘nested’ next is array so at 0 position of that array.(In case of object it will tell key in case of array it will tell index)

source : it gives what values of source is there

target : it shows what values of target is there

index: it tells the after source_trace exact location of issue.

So in our code there are two mis match so it brings out two objects.

I have created these algorithm for for type checking in complete schema provided.You can use this code modify it for different object comparison like finding if any null, undefined values are there or you want to check type plus values also.

Used DFS (Depth first search approach) for searching elements exploring depth firsts then it’s child. Here in javascript there are two flows for searching for object and array you can modify that for your language.

Used stack for maintaining trace path and bring back trace path of issues.

DONE

--

--