Handlebars helper to compare two arrays and return the difference

handlebars.js, html, javascript

Solution

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}}

Problem

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> ```

Original source

Related problems