This content originally appeared on Go Make Things and was authored by Go Make Things
In yesterday’s article, we looked at how to check if an array includes all of the values from another.
As I was writing it, I quickly realized that if I were attempting that task with PHP, I might use the array_intersect()
function, which returns a new array containing the overlapping values between two different arrays.
JavaScript doesn’t have an Array.intersect()
method, so today I thought we’d create one.
First, let’s create an arrayIntersect()
function. We’ll accept two arrays, arr1
and arr2
, as arguments.
/**
* Get the intersecting values between two arrays
* @param {Array} arr1 The first array
* @param {Array} arr2 The second array
* @return {Array} The array of overlapping values
*/
function arrayIntersect (arr1, arr2) {
// ...
}
Next, let’s use the Array.filter()
method to create a new array containing just our overlapping values.
We’ll run it on the first array, arr1
.
/**
* Get the intersecting values between two arrays
* @param {Array} arr1 The first array
* @param {Array} arr2 The second array
* @return {Array} The array of overlapping values
*/
function arrayIntersect (arr1, arr2) {
return arr1.filter();
}
Inside the callback function, we’ll check if the current item
is in the second array, arr2
, using the Array.includes()
method. If it does, we’ll include it in our new array.
/**
* Get the intersecting values between two arrays
* @param {Array} arr1 The first array
* @param {Array} arr2 The second array
* @return {Array} The array of overlapping values
*/
function arrayIntersect (arr1, arr2) {
return arr1.filter(function (item) {
return arr2.includes(item);
});
}
Now, you can do something like this.
let wizards = ['Merlin', 'Gandalf', 'Ursula'];
let magicalFolk = ['Gandalf', 'Radagast', 'Ursula', 'Morgana'];
// returns ["Gandalf", "Ursula"]
let overlap = arrayIntersect(wizards, magicalFolk);
You can find this one on the Vanilla JS Toolkit.
Level-up your team’s core JavaScript skills. I offer project-based courses and workshops designed to fit around your team's schedule. It's perfect for remote and distributed teams.
This content originally appeared on Go Make Things and was authored by Go Make Things
Go Make Things | Sciencx (2022-10-12T14:30:00+00:00) How to find the intersecting values of two arrays with vanilla JavaScript. Retrieved from https://www.scien.cx/2022/10/12/how-to-find-the-intersecting-values-of-two-arrays-with-vanilla-javascript/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.