3

I am new to handlebars.js and I need a handlebars helper to compare two arrays and return the difference.


I have tried the example but it is not working for me. I think I'm making some mistake. Please find my code below and correct me.

Javascript

var subscriptionInfo = {   
    subscription : "oldFeature",
    feature : {
        oldFeature : ["1 Free Projects", "10 MB Storage Space", "Project Feeds","Task   Management"],
        newFeature : ["10 Free Projects", "1 GB Storage Space", "Project Feeds","Task Management"]  
    }

Template

<ul class='featureList'>
    {{#feature}}
        {{#oldFeature}}
            <li class="{{arraysDiff ../oldFeatur ../newFeature}} myclass {{arraysDiff}}">{{.}}</li>
        {{/oldFeature}}
    {{/feature}}  
</ul>
iConnor
  • 19,997
  • 14
  • 62
  • 97
prakashstar42
  • 677
  • 1
  • 6
  • 16
  • Please, include a better description with samples and some code with what you have tried so far. This would help others better understand your exact problem. For example, what is inside the arrays? Numbers? Strings? Objects? – veducm Jan 28 '14 at 10:52
  • This isn't anything to do with [tag:JSON]... – iConnor Mar 05 '14 at 02:33

1 Answers1

4

First thing you will need is a method to calculate the two arrays difference. Depending on the type of arrays that your are comparing, you may need a different method to obtain the array with the difference. In this example, I will use the method explained in this other SO answer.

function arr_diff(a1, a2)
{
    var a=[], diff=[];      
    for(var i = 0; i < a1.length; i++) {
        a[a1[i]] = true;
    }
    for(var i = 0; i < a2.length; i++) {
        if (a[a2[i]]) 
            delete a[a2[i]];
        else 
            a[a2[i]] = true;
    }
    for(var k in a) {
        diff.push(k);
    }
    return diff;
}

Then, you can register your Handlebars helper to use the above method as follows:

Handlebars.registerHelper('arraysDiff', function(arrayA, arrayB, opts) 
{
    var result = arr_diff(arrayA, arrayB);
    return opts.fn(result);
});

And finally, you can just use this helper in your Handlebars template:

{{#arraysDiff this.jsonArray1 this.jsonArray2}}

    <!-- Do something with the difference array, e.g. print it -->
    {{this}}

{{/arraysDiff}}
Community
  • 1
  • 1
veducm
  • 5,933
  • 2
  • 34
  • 40
  • Thanks for reply. Think given example will work for me, else i'll reply with proper example code. – prakashstar42 Jan 28 '14 at 11:35
  • Great! Just let me know if it does not. Also, remember to vote up the answer if it helped you and to mark it as accepted if it is the correct answer to your question. Thanks! – veducm Jan 28 '14 at 11:59