Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 7 of 7
  1. #1
    New to the CF scene
    Join Date
    Sep 2013
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Comparing Arrays if there is a match

    Code:
    url = ["http://www.linkedin.com/in/jannuelanarna", "http://www.linkedin.com/in/iefiekasd", "http://www.linkedin.com/in/uad123asd", undefined, undefined];
    Code:
    publicUrl = ["http://www.linkedin.com/in/jannuelanarna", "http://www.linkedin.com/pub/jay-r-bautista/64/b29/45b", undefined, "http://www.linkedin.com/pub/ronilo-canson/75/927/4a3", "http://www.linkedin.com/pub/siddharth-chaudhary/33/aa1/8", "http://www.linkedin.com/in/rojohnh", "http://www.linkedin.com/pub/lara-martinez/74/777/a3b", "http://www.linkedin.com/pub/alena-ortega/69/72a/415", "http://www.linkedin.com/in/nivlek1416", "http://www.linkedin.com/pub/emmar-reveriza/59/a91/132", "http://www.linkedin.com/in/samsanchezcb", "http://www.linkedin.com/pub/mitch-stevens/6b/375/3a0", "http://www.linkedin.com/pub/irish-jane-sumadic/29/339/910", "http://www.linkedin.com/pub/joel-sumadic/45/31b/ab3", "http://www.linkedin.com/pub/luna-cielo-yniesta/68/4b2/690"];

    Hello there. I'm having problems comparing two javascript arrays, what I want is :

    1) Compare url & publicUrl
    2) If there is a match e.g. there are two jannuelnarna, then alert me if there is a match if not alert no match too.

    Quite simple but I can't seem to formulate a logic.

  • #2
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,020
    Thanks
    75
    Thanked 4,323 Times in 4,289 Posts
    Code:
    var url = ...
    var publicUrl = ...
    
    var match = false;
    for ( var u = 0; u < url.length; ++u )
    {
        var check = url[u].toLowerCase();
        for ( var p = 0; p < publicUrl.length; ++p )
        {
            if ( check == publicUrl[p].toLowerCase() )
            {
                match = true;
                break; //exit the for
            }
        }
        if ( match ) break; // exit outer for
    }
    alert( ( match ? "Found" : "Did not find" ) + " a match");
    You may omit both uses of .toLowerCase() if you want the match to be exact (case sensitive).

    This not very efficient code, but so long as the two arrays aren't very long it's adequate.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #3
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,184
    Thanks
    10
    Thanked 569 Times in 550 Posts
    there a really simple way to do it these days:

    Code:
    url = ["http://www.linkedin.com/in/jannuelanarna", "http://www.linkedin.com/in/iefiekasd", "http://www.linkedin.com/in/uad123asd", undefined, undefined];
    
    publicUrl = ["http://www.linkedin.com/in/jannuelanarna", "http://www.linkedin.com/pub/jay-r-bautista/64/b29/45b", undefined, "http://www.linkedin.com/pub/ronilo-canson/75/927/4a3", "http://www.linkedin.com/pub/siddharth-chaudhary/33/aa1/8", "http://www.linkedin.com/in/rojohnh", "http://www.linkedin.com/pub/lara-martinez/74/777/a3b", "http://www.linkedin.com/pub/alena-ortega/69/72a/415", "http://www.linkedin.com/in/nivlek1416", "http://www.linkedin.com/pub/emmar-reveriza/59/a91/132", "http://www.linkedin.com/in/samsanchezcb", "http://www.linkedin.com/pub/mitch-stevens/6b/375/3a0", "http://www.linkedin.com/pub/irish-jane-sumadic/29/339/910", "http://www.linkedin.com/pub/joel-sumadic/45/31b/ab3", "http://www.linkedin.com/pub/luna-cielo-yniesta/68/4b2/690"];
    
    
    
    alert( String(publicUrl.filter(function(a){
       return a && this.indexOf(a)!==-1;
    }, url ) )  || "no matches" );
    anon logic need no vars or loops or conditionals, and you can optionally export the main logic as a named function for later recycling.
    if you have an array contains method like _.contains(), there's no user logic code:

    Code:
    _.filter(_.filter(publicUrl, eval.call.bind(_.contains, url, url) ), Boolean)
    Last edited by rnd me; 09-10-2013 at 09:16 PM.
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/1/19) IE7:0.2, IE8:6.7, IE11:7.4, IE9:3.8, IE10:4.4, FF:18.3, CH:43.6, SF:7.8, MOBILE:27.5

  • #4
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,020
    Thanks
    75
    Thanked 4,323 Times in 4,289 Posts
    "really simple". Hmmm... I know some PhD's who wouldn't get that. (Okay, so they happen to be PhD's in English. <grin/>)

    *I* understand that, RndMe, but do you really think a newbie to JS will??

    Anyway, if you are going to present code like that to newbies, it would be worth explaining how and why it works. Even if people don't "get" it the first time, the explanation will percolate through eventually.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #5
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,184
    Thanks
    10
    Thanked 569 Times in 550 Posts
    Quote Originally Posted by Old Pedant View Post
    Anyway, if you are going to present code like that to newbies, it would be worth explaining how and why it works. Even if people don't "get" it the first time, the explanation will percolate through eventually.
    i hope they can understand it. i have virtually no CS education and it reads like a headline to me. i know i'm weird like that though...
    i don't support underscore, so let's walk-through my code backwards:
    Code:
    alert( String(publicUrl.filter(function(a){
       return a && this.indexOf(a)!==-1;
    }, url ) )  || "no matches" );
    we all know what alert does, so let's kill that:

    Code:
    String(publicUrl.filter(function(a){
       return a && this.indexOf(a)!==-1;
    }, url ) )  || "no matches" ;


    String will convert whatever's inside to a string, in this case, everything.
    it turns an array into a string in my code.
    if that array is empty, the resulting string will be "", an empty string.
    if that string is empty, it evaluates to false when coerced as a boolean.
    this is how the error message gets toggled when there are no matches.

    the default operator, "||", will evaluate to the left hand side first, and if that's false, the right-side will be returned.

    let's kill the string coercion and "no matches" warning to simplify our core logic:

    Code:
    publicUrl.filter(function(a){
       return a && this.indexOf(a)!==-1;
    }, url ) ;
    now were getting to the heart of the beast.

    publicUrl is a list of all valid URLs. if we strip down that list so that only items that are also in the "url" array are present, we are left with a list of valid urls that are in the to-be-checked array. or so my theory goes.

    so, we want to filter publicUrl to remove anything that's invalid or not in url.
    we use filter to run a function on each element in the array.
    if that function returns false-ish, the element is not included in the output array.
    if that function returns true-ish, the element is included in the output array.

    we can specify "this" inside that function, passing a 2nd argument to [].filter that will be known as "this" inside the walls of the function. in that manner, we don't need to hard-code "url" into our logic, we inject that dependency in later, at call time. this allows for cleaner and more-reusable and testable code.

    the argument "a" is a stand-in for each element of the array inside the walls of the function.

    inside our custom logic, coded as a function we pass to [].filter, we use indexOf to see if each item in publicUrl is also in url.
    since indexOf returns a -1 for a miss, and [].filter needs a boolean, we must use our single line of actual program code to convert -1 to false.

    before that step, we can throw away any empty elements in the array using "a &&".
    if a is empty it's false-ish, and the "&&" operator stops, returning false, which causes filter to discard the element.

    it's harder to explain than it is to code, but once you start using [].filter/[].map/[].reduce, everything starts looking like an array; ex: Object.keys(obj).map(...)...
    that's really the key; it's hard to explain because the tiny built-in pieces are doing so much heavy lifting, that you have to explain native code.
    once you learn the little pieces like [].indexOf, [].filter, etc, you can use these code stacks to substitute for your own hand-written logic.

    compared to a for loop for example, you don't need specify/init the boiler place of a loop increment-er, an index cap, an output variable, a slot placeholder, or the setup of a Boolean comparison...

    in short, these newer utilities are some of the best parts of js, reducing clutter and boilerplate while allowing much easier building of modular, transparent, and testable routines.
    Last edited by rnd me; 09-10-2013 at 10:26 PM.
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/1/19) IE7:0.2, IE8:6.7, IE11:7.4, IE9:3.8, IE10:4.4, FF:18.3, CH:43.6, SF:7.8, MOBILE:27.5

  • The Following 2 Users Say Thank You to rnd me For This Useful Post:

    Dormilich (09-11-2013), Old Pedant (09-10-2013)

  • #6
    New Coder
    Join Date
    Aug 2013
    Posts
    50
    Thanks
    0
    Thanked 11 Times in 11 Posts
    I would do it using forEach. It's pretty readable, simple, and well supported across browsers (excluding a couple... *points at IE*).

    Code:
    // iterate through each key of 'publicUrl'
    publicUrl.forEach(function (u) {
    
        // if a URL in 'publicUrl' was found in 'url'
        if (url.indexOf(u) !== -1) {
    
            // then do something with 'u' (the URL found)
            alert('Match found!\n\n' + u);
    
        }
    
    });

  • #7
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,020
    Thanks
    75
    Thanked 4,323 Times in 4,289 Posts
    Quote Originally Posted by rnd me View Post
    i hope they can understand it. i have virtually no CS education and it reads like a headline to me. i know i'm weird like that though...
    LOL! Indeed you are!

    But that was a WONDERFUL explanation. Well worth your time writing it, in my opinion!

    p.s.: CS education? What's that? There were no CS undergraduate majors when I was in college, and only a handful of graduate programs. My college programming education consisted of one course in Fortran, where I think I understood it better than the instructor. I did take one graduate class in computers, but it was 100% *HARDWARE* logic circuits. So far as I remember, there weren't any software courses at that school (University of Southern California, USC, by the by).
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.


  •  

    Tags for this Thread

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •