Equals //JavaScript Repository

Description

Tests if two or more objects are equal, accepts any type of object, even multidimensional arrays.
Created: 2005.12.26

Code (Download)

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/geral/equals [rev. #1]

equals = function(a, b){
    for(var j, o = arguments, i = o.length, c = a instanceof Object; --i;)
        if(a === (b = o[i]))
            continue;
        else if(!c || !(b instanceof Object))
            return false;
        else for(j in b)
            if(!equals(a[j], b[j]))
                return false;
    return true;
};

Example (Example)

<script type="text/javascript">
//<![CDATA[

document.write(
    "equals(1, 2, 3, 4) = ".bold(), equals(1, 2, 3, 4), "<br />",
    "equals(1, 1, 1, 1) = ".bold(), equals(1, 1, 1, 1), "<br />",
    "equals({a: 1, b: 0}, {b: 0, a: 1}) = ".bold(), equals({a: 1, b: 0}, {b: 0, a: 1}), "<br />",
    "equals({a: 1, b: 0}, {a: 1, b: null}) = ".bold(), equals({a: 1, b: 0}, {a: 1, b: null}), "<br />",
    "equals([1, 2, 3], [3, 2, 1]) = ".bold(), equals([1, 2, 3], [3, 2, 1]), "<br />",
    "equals([1, 2, 3], [1, 2, 3]) = ".bold(), equals([1, 2, 3], [1, 2, 3]), "<br />",
    "equals([[1],2,[3]], [1,2,3]) = ".bold(), equals([[1],2,[3]], [1,2,3]), "<br />"
);

//]]>
</script>

Help

equals(a: Object, b: Object): Boolean
Analyzes two or more objects and, returns true if they are equal (contain the same properties with the same values).
a
object to analyze
b
object to analyze
...
infinite amount of objects

Rank (Votes: 7)

2.00