Tag: Javascript

  • WordPress: Underscore And Lodash Conflict

    In one of the projects that I’m working on, I recently encountered a conflict between Underscore library used within WordPress and the Lodash library used with the Theme I was working on.

    I knew from the console errors that the conflict arises because both use _. syntax. I knew that I must use _.noConflict() but I didn’t know where to.

    One of my fellow developers came up with the following solution to solve the issue.

    wp_enqueue_script( 'et-onboarding', $BUNDLE_URI, $BUNDLE_DEPS, (string) $cache_buster, true );
    
    wp_add_inline_script( 'et-onboarding', '_.noConflict(); _.noConflict();', 'after' );
    
    wp_localize_script( 'et-onboarding', 'et_onboarding_data', self::get_onboarding_helpers() );

    I’m fortunate to be part of a team of brilliant folks.

  • Javascript: Remove Duplicates From Arrays — A Simple Way

    Let us dive right away with an example.

    const urls = [
        "https://example.com/premade/wp-content/uploads/sites/4/2023/11/800x800.jpg",
        "https://example.com/premade/wp-content/uploads/sites/4/2023/11/800x800.jpg",
        "https://example.com/premade/wp-content/uploads/sites/4/2023/11/800x800.jpg",
        "https://example.com/premade/wp-content/uploads/sites/4/2023/11/800x800.jpg",
        "https://example.com/premade/wp-content/uploads/sites/4/2023/11/800x800.jpg",
        "https://example.com/premade/wp-content/uploads/sites/4/2023/11/800x800.jpg",
        "https://example.com/premade/wp-content/uploads/sites/4/2023/11/800x800.jpg",
        "https://example.com/premade/wp-content/uploads/sites/4/2023/11/800x800.jpg"
    ];
    
    const uniqueUrls = [...new Set(urls)];
    
    console.log(uniqueUrls);
    

    Now the question is — how does a Set object remove duplicates? Set objects are collections of values. A value in the set may only occur once; it is unique in the set’s collection.

    Note that our array urls must be converted to set and then back to array. The conversion is very simple.

    const myArray = ["value1", "value2", "value3"];
    
    // Use the regular Set constructor to transform an Array into a Set
    const mySet = new Set(myArray);
    
    mySet.has("value1"); // returns true
    
    // Use the spread syntax to transform a set into an Array.
    console.log([...mySet]); // Will show you exactly the same Array as myArray