Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>There is no easy way to do this. I needed this as well, but wanted a function that can take any two variables and test for equality. That includes non-object values, objects, arrays and any level of nesting. </p> <p>In your question, you mention wanting to ignore the order of the values in an array. My solution doesn't inherently do that, but you can achieve it by sorting the arrays before comparing for equality</p> <p>I also wanted the option of casting non-objects to strings so that [1,2]===["1",2]</p> <p>Since my project uses UnderscoreJs, I decided to make it a mixin rather than a standalone function. </p> <p>You can test it out on <a href="http://jsfiddle.net/nemesarial/T44W4/" rel="nofollow">http://jsfiddle.net/nemesarial/T44W4/</a></p> <p>Here is my mxin:</p> <pre><code>_.mixin({ /** Tests for the equality of two variables valA: first variable valB: second variable stringifyStatics: cast non-objects to string so that "1"===1 **/ equal:function(valA,valB,stringifyStatics){ stringifyStatics=!!stringifyStatics; //check for same type if(typeof(valA)!==typeof(valB)){ if((_.isObject(valA) || _.isObject(valB))){ return false; } } //test non-objects for equality if(!_.isObject(valA)){ if(stringifyStatics){ var valAs=''+valA; var valBs=''+valB; ret=(''+valA)===(''+valB); }else{ ret=valA===valB; } return ret; } //test for length if(_.size(valA)!=_.size(valB)){ return false; } //test for arrays first var isArr=_.isArray(valA); //test whether both are array or both object if(isArr!==_.isArray(valB)){ return false; } var ret=true; if(isArr){ //do test for arrays _.each(valA,function(val,idx,lst){ if(!ret){return;} ret=ret &amp;&amp; _.equal(val,valB[idx],stringifyStatics); }); }else{ //do test for objects _.each(valA,function(val,idx,lst){ if(!ret){return;} //test for object member exists if(!_.has(valB,idx)){ ret=false; return; } // test for member equality ret=ret &amp;&amp; _.equal(val,valB[idx],stringifyStatics); }); } return ret; } }); </code></pre> <p>This is how you use it:</p> <pre><code>_.equal([1,2,3],[1,2,"3"],true) </code></pre> <p>To demonstrate nesting, you can do this:</p> <pre><code>_.equal( ['a',{b:'b',c:[{'someId':1},2]},[1,2,3]], ['a',{b:'b',c:[{'someId':"1"},2]},["1",'2',3]] ,true); </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload