Q:

Need some ideas on how to use functional programming in JavaScript to reuse a function

Here is my jsfiddle: https://jsfiddle.net/kpam8g79/9/
I have a function findCommon:
function findCommon(ar1, ar2, ar3)
{
    // Initialize starting indexes for ar1[], ar2[] and ar3[]
    let i = 0, j = 0, k = 0;

    // Iterate through three arrays while all arrays have elements
    while (i < ar1.length && j < ar2.length && k < ar3.length)
    {
         // If x = y and y = z, print any of them and move ahead
         // in all arrays
         if (ar1[i] == ar2[j] && ar2[j] == ar3[k])
         {   console.log(ar1[i]+" ");   i++; j++; k++; }

         // x < y
         else if (ar1[i] < ar2[j])
             i++;

         // y < z
         else if (ar2[j] < ar3[k])
             j++;

         // We reach here when x > y and z < y, i.e., z is smallest
         else
             k++;
    }
}

My data set looks like this:
const ar1 = [1, 2, 3, 6, 8];

But when my dataset is an array of objects
const oAr1 = ar1.map(v => ({value: v, display: `value ${v}`}));

I still want to get the common values.
I can map oAr1 into ar1 and call the findCommon function, but that might not be performant.  I can also modify the findCommon function to take in the array of objects instead of an array of numbers, but I want to reuse findCommon.  I was wondering if I can use functional programming to somehow compose two functions so that I can reuse findCommon.
I wonder how this can be done...

A:

You could add an optional parameter to your findCommon that defaults to x => x.
This allows you to pass a function that describes the logic required to find the value to compare.

const ar1 = [1, 2, 3, 6, 8];
const ar2 = [1, 5, 6, 9];
const ar3 = [1, 4, 5, 6];

const oAr1 = ar1.map(v => ({value: v, display: `value ${v}`}));
const oAr2 = ar2.map(v => ({value: v, display: `value ${v}`}));
const oAr3 = ar3.map(v => ({value: v, display: `value ${v}`}));

findCommon(ar1, ar2, ar3);
findCommon(oAr1, oAr2, oAr3, o => o.value);

function findCommon(ar1, ar2, ar3, getValue = x => x)
{
    // Initialize starting indexes for ar1[], ar2[] and ar3[]
    let i = 0, j = 0, k = 0;

    // Iterate through three arrays while all arrays have elements
    while (i < ar1.length && j < ar2.length && k < ar3.length)
    {
         var x1 = getValue(ar1[i]);
         var x2 = getValue(ar2[j]);
         var x3 = getValue(ar3[k]);
         
         // If x = y and y = z, print any of them and move ahead
         // in all arrays
         if (x1 === x2 && x2 === x3)
         {   console.log(x1, ar1[i]);   i++; j++; k++; }

         // x < y
         else if (x1 < x2)
             i++;

         // y < z
         else if (x2 < x3)
             j++;

         // We reach here when x > y and z < y, i.e., z is smallest
         else
             k++;
    }
}

