Search code examples
javascriptarraysstringadobe-indesignextendscript

Compare arrays with strings (match parts of strings)


I'm working on an InDesign script and need to compare two arrays with strings returning a new array with A + B elements that doesn't match A elements.

For example:

var a = ['LFC_Luis Felipe Corullon', 'FTP', 'WWW'];
var b = ['SEMA', 'LFC', 'HTTP', 'AVC'];

I need as result this:

['LFC_Luis Felipe Corullon', 'FTP', 'WWW', 'SEMA', 'HTTP', 'AVC']

Excluding 'LFC' because it matches with 'LFC_Luis Felipe Corullon'.

I tried this, but it loops forever...

var a = ["LFC_Luis Felipe Corullón" , "FTP" , "FMTP"];
var b = ["LFC" , "FDOT" , "SAS" , "ADA" , "SAE"];
//========================================================================================
alert(merge(a,b));

function merge(a,b) {
    var r = a;
    for (var i=0; i<a.length; i++) {
        var v = [];
        for (var j=0; j<b.length; j++) {
            if ( a[i].split("_")[0] == b[j] ) v.push(true);
            else v.push(false);
            }
        for (k in v) {
            if (v[k]==false) r.push(b[k]);
            }
        }
    return r;
    }

Any help? Thanks in advance.


Solution

  • I'm used to do it this way:

    var a = ['LFC_Luis Felipe Corullon', 'FTP', 'WWW'];
    var b = ['SEMA', 'LFC', 'HTTP', 'AVC'];
    
    var a_str = a.join('\t'); // convert the array into a string
    
    for (var i in b) if (a_str.indexOf(b[i])<0) a.push(b[i]);
    
    console.log(a); // or alert(a);

    It can be even an one-liner if you don't care the performance:

    var a = ['LFC_Luis Felipe Corullon', 'FTP', 'WWW'];
    var b = ['SEMA', 'LFC', 'HTTP', 'AVC'];
    
    for (var i in b) if (a.join('\t').indexOf(b[i])<0) a.push(b[i]);
    
    console.log(a);

    The second solution, by the way, eliminates duplicated values from the result array:

    var a = ['LFC_Luis Felipe Corullon', 'FTP', 'WWW'];
    var b = ['LFC', 'AVC', 'AVC', 'AVC']; // <-- duplicates
    

    result:

    [ 'LFC_Luis Felipe Corullon', 'FTP', 'WWW', 'AVC' ] // <-- no duplicates
    

    If you want to use RegExp to find matches it can be done this way:

    var a = ['LFC_Luis Felipe Corullon', 'FTP', 'WWW'];
    var b = ['SEMA', 'LFC', 'ftp', 'HTTP', 'AVC'];
    
    var a_str = a.join('\t'); // convert the array into a string
    
    for (var i in b) {
        var reg = new RegExp(b[i], 'i'); // 'i' to ingore case for example
        if (!a_str.match(reg)) a.push(b[i]);
    }
    
    console.log(a);