Skip to main content
1 of 5
Tushar
  • 3k
  • 1
  • 21
  • 28

Naming

a, b, what are not meaningful, descriptive and searchable names. arr1, arr2 and needle are descriptive names.

Code Duplication

There are two for loops in countInArray and both are same. A function can be created which will take array and needle as arguments and return the count.

Implicit globals

In below code, x is global. Since, var is not used to declare the variable, it is added to global scope. To make it local to function use var. See Why are global variables considered bad practice?

  for (x = 0; x < b.length; x++) {
      if (!a.includes(b[x]) && !arr.includes(b[x]))
          arr.push(b[x])
  }

Missing Semi-Colons

Although a minor thing, but this could lead to unexpected results in some cases. I recommend to add semi-colons explicitly and not rely on automatic semicolon insertion. See What are the rules for JavaScript's automatic semicolon insertion (ASI)?

Taking advantage of ES2015

include is used in code which means that your environment supports ES2015. However, you're not taking advantage of ES2015 features.


With the last point above, I'll suggest you to use below equivalent code

function customMergeArrays(arr1, arr2) {
    'use strict';

    var elementCount = (haystack, needle) => haystack.filter(el => el === needle).length;
    var uniqueElements = [...new Set(arr1.concat(arr2))];

    var result = [];
    uniqueElements.forEach(function(el) {
        var aIncludes = arr1.includes(el);
        var bIncludes = arr2.includes(el);

        if ((aIncludes && bIncludes === false) || (aIncludes === false && bIncludes)) {
            result.push(el);
        } else if (aIncludes && bIncludes && elementCount(arr1, el) === elementCount(arr2, el)) {
            result.push(el);
        }
    });
    return result.sort((a, b) => a - b);
}

var firstArr = [1, 3, 40, 40, 50, 60, 60, 60];
var secondArr = [2, 40, 40, 50, 50, 65];
var mergedArray = customMergeArrays(firstArr, secondArr);
console.log(mergedArray);

Explanation:

elementCount is the function that uses new Arrow function and returns the count of the element occurred in the array. This method accepts array and element to search.

[...new Set(arr1.concat(arr2))] first concats two arrays and pass it to Set and using spread syntax array of unique elements is created from set.

Then, iterating over this array of unique elements and push them into results array by checking the conditions.

To compare the performance, I've created JSPerf test.

Here's screenshot for reference.

enter image description here

Tushar
  • 3k
  • 1
  • 21
  • 28