Converting my favourite PHP functions to JavaScript - Part 1: array_diff

I recently transitioned from being a Full Stack Software Developer, to a Front End Software Developer. Now, I work in a pure JavaScript/Typescript codebase, and I'm beginning to miss some of my favourite PHP functions.

This will be a mini series where I'll convert some of my favourite PHP functions into a JavaScript function. 

In this one, I'll be focusing on converting the array_diff() function.

In short, array_diff() takes in at least 2 arrays, the first array is the array to compare from, and all following arrays is what will be searched.

The fun part of array_diff() is that it can take any number of parameters, meaning you could actually use it like this:

It isn't anything crazy, so converting this function to JavaScript is a simple task.

First, we allow the arrayDiff() arrow function to take in any number of arguments by using the spread operator.

As this spread operator would convert it into an array of arrays, e.g. [[1], [2], [3]]... we want to flatten this into 1 array. We can do this quite simply by using the concat() method.

Lastly, we use the filter() method on the firstArray argument, which is the array we want to use to compare. This will loop over firstArray, and the !allArrays.includes(item) line will filter out any items it comes across that appear within allArrays.

Use Case

My main use case of this function in PHP is usually when I'm sending a big chunk of data through to the back end, and want to check if there are items in the database that should be deleted based on the data sent through.