Find Values in Common Between Two Arrays

How can I find matching values in two arrays?

Naturally, my approach was to loop through the first array once and check the index of each value in the second array. If the index is > -1, then push it onto the returned array.

​Array.prototype.diff = function(arr2) {
var ret = [];
for(var i in this) {
if(arr2.indexOf(this[i]) > -1){
ret.push(this[i]);
}
}
return ret;
};


My solution doesn't use two loops like others do so it may run a bit faster. If you want to avoid using for..in, you can sort both arrays first to reindex all their values:

Array.prototype.diff = function(arr2) {
var ret = [];
this.sort();
arr2.sort();
for(var i = 0; i < this.length; i += 1) {
if(arr2.indexOf(this[i]) > -1){
ret.push(this[i]);
}
}
return ret;
};

Usage would look like:

var array1 = ["cat", "sum","fun", "run", "hut"];
var array2 = ["bat", "cat","dog","sun", "hut", "gut"];

console.log(array1.diff(array2));

If you have an issue/problem with extending the Array prototype, you could easily change this to a function.

var diff = function(arr, arr2) {

And you'd change anywhere where the func originally said this to arr2.

Find values in common between two arrays

You can use the set intersection method & for that:

x = [1, 2, 4]
y = [5, 2, 4]
x & y # => [2, 4]

Finding Common Values While Looping Over Two Arrays

You can reduce the 1st array and use a forEach loop over the second array to see if each of the values are equal, then push the value to the accumulator:

const arr1 = [{ kind: 'E', path: [ 'short_name' ], lhs: 'testing', rhs: 'testing1' }, { kind: 'E', path: [ 'agent_name' ], lhs: 'testing', rhs: 'testing2' }]const arr2 = [{ lhs: 'legacyId', rhs: 'id_number' }, { lhs: 'name.short', rhs: 'short_name' }, { lhs: 'name.long', rhs: 'agent_name' }, { lhs: 'gender', rhs: 'gender' }, { lhs: 'dob', rhs: 'date_of_birth' }]
const common = arr1.reduce((a, o1) => { const match = arr2.find(o2 => o1.path[0] === o2.rhs) match && a.push(match.rhs) return a}, [])
console.log(common)

How to get common values from two different arrays in PHP

Native PHP functions are faster than trying to build your own algorithm.

$result = array_intersect($array1, $array2);

Comparing Two Arrays with Array.filter and Pushing to New Arrays Based on Common Values

Try this, which uses Array.prototype.find to test for whether an object exists in arr2 with a given id:

const arr1 = [{id: 1}, {id: 2}, {id: 3}];const arr2 = [{id: 3}, {id: 4}, {id: 5}];
const recordsToUpdate = arr1.filter(e => arr2.find(obj => obj.id === e.id) !== undefined);const recordsToInsert = arr1.filter(e => arr2.find(obj => obj.id === e.id) === undefined);
console.log('recordsToUpdate: ', recordsToUpdate);console.log('recordsToInsert: ', recordsToInsert);

Find common count by comparing 2 arrays

Yes, there is a lodash function named intersection.

So, below is the code you can use to find the length of the common values of two arrays.

arr1 = [1,2,3]
arr2 = [2,3,4]

console.log(_.intersection(arr1, arr2).length);

How do I find a common element between two arrays in JavaScript?

This is a data structure problem.
You can simply create an object for Array1, and then search for the keys in Object which are in Array2.

Array1 = ['Apple','Orange','Grape'];

Array2 = ['Apple','Lemon','Mango','Grape'];

array1 = ['Apple','Orange','Grape'];

array2 = ['Apple','Lemon','Mango','Grape'];

let obj = {};

for (let fruit of array1) {
obj[fruit] = 1;
}

let commonArray = [];

array2.forEach(fruit => {
if (obj[fruit] === 1) {
commonArray.push(fruit);
}
})

common array will contain Apple and Grape;

Javascript Program for find common elements in two array

Since the arrays are sorted, binary search is the key.

Basically, you're searching an item in an array.

You compare the item against the middle index of the array (length / 2)

If both are equal, you found it.

If item is inferior than the one at the middle index of the array, compare item against the index being at index length / 4 -> ((0 + length / 2) / 2), if it's inferior, at index ((length / 2) + length) / 2 (the middle of upper part) and so on.

That way, if in example you have to search item in a 40 000 length array, at worse, you find out that item isn't in the array with 16 comparisons :

I'm searching for "something" in an array with 40 000 indexes, minimum index where I can find it is 0, the maximum is 39999.

"something" > arr[20000]. Let's assume that. I know that now the minimum index to search is 20001 and the maximum is 39999. I'm now searching for the middle one, (20000 + 39999) / 2.

Now, "something" < arr[30000], it limits the search from indexes 20001 to 29999. (20000 + 30000) / 2 = 25000.

"something" > arr[25000], I have to search from 25001 to 29999. (25000 + 30000) / 2 = 27500

"something" < arr[27500], I have to search from 25001 to 27499. (25000 + 27500) / 2 = 26250

"something" > arr[26250], I have to search from 26251 to 27499. (26250 + 27500) / 2 = 26875

"something" < arr[26875], I have to search from 26251 to 26874. (26250 + 26875) / 2 = 26563

And so on... Of course, you have to round and stuff to avoid floating indexes

var iteration = 1;

function bSearch(item, arr)
{
var minimumIndex = 0;
var maximumIndex = arr.length - 1;
var index = Math.round((minimumIndex + maximumIndex) / 2);

while (true)
{
++iteration;
if (item == arr[index])
{
arr.splice(0, minimumIndex);
return (true);
}
if (minimumIndex == maximumIndex)
{
arr.splice(0, minimumIndex);
return (false);
}
if (item < arr[index])
{
maximumIndex = index - 1;
index = Math.ceil((minimumIndex + maximumIndex) / 2);
}
else
{
minimumIndex = index + 1;
index = Math.floor((minimumIndex + maximumIndex) / 2);
}
}
}

var arrA;
var arrB;

for (var i = 0; i < arrA.length; ++i)
{
if (bSearch(arrA[i], arrB))
console.log(arrA[i]);
}
console.log("number of iterations : " + iteration);


Related Topics



Leave a reply



Submit