Finding What Is Common to Two Arrays

Finding what is common to two arrays

You can intersect the arrays using &:

array1 & array2

This will return ["pig", "dog", "cat"].

Finding common elements in two arrays of different size

Sort the arrays. Then iterate through them with two pointers, always advancing the one pointing to the smaller value. When they point to equal values, you have a common value. This will be O(n log n+m log m) where n and m are the sizes of the two lists. It's just like a merge in merge sort, but where you only produce output when the values being pointed to are equal.

def common_elements(a, b):
a.sort()
b.sort()
i, j = 0, 0
common = []
while i < len(a) and j < len(b):
if a[i] == b[j]:
common.append(a[i])
i += 1
j += 1
elif a[i] < b[j]:
i += 1
else:
j += 1
return common

print 'Common values:', ', '.join(map(str, common_elements([1, 2, 4, 8], [1, 4, 9])))

outputs

Common values: 1, 4

If the elements aren't comparable, throw the elements from one list into a hashmap and check the elements in the second list against the hashmap.

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)

Finding common exact elements in two arrays

I ran your exact code in swift playground and get newArray equaling an empty array. This is because the firstArray contains only one object, the String

"9,54,59,60,66,362,372,399,400,411,428"

The commas do not break the string up into smaller strings or integers. All the characters inside the quotation marks are part of the string including commas.

The secondArray also only contains one string

"9,40,62,399"

Filtering the firstArray tests whether the string "9,40,62,399" contains the string "9,54,59,60,66,362,372,399,400,411,428", which is false, and so the newArray is empty.

If you remove the quotes at the beginning and end inside of the arrays then all the numbers are Ints and the same function returns newArray with only matches [9, 399].

For Int

let firstArray = [9,54,59,60,66,362,372,399,400,411,428]
let secondArray = [9,40,62,399]

let newArray = firstArray.filter { (string) -> Bool in
return secondArray.contains(string)
}
// Returns [9, 399]

For Strings

let firstArray = ["9","54","59","60","66","362","372","399","400","411","428"]
let secondArray = ["9","40","62","399"]

let newArray = firstArray.filter { (string) -> Bool in
return secondArray.contains(string)
}
// Returns ["9", "399"]

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);

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.

How to find common elements only between 2 arrays in Angular 2

Use Array#filter method and inside filter function use Array#indexOf or Array#includes methods to check second array includes the element.

var array1 = [1, 2, 3, 4, 5, 6];

var array2 = [1, 2, 3, 4, 5, 6, 7, 8, 9];

var res = array1.filter(function(v) { // iterate over the array

// check element present in the second array

return array2.indexOf(v) > -1;

// or array2.includes(v)

})

console.log(res);

How to find common elements in two arrays?

There is an array_intersect function that does pretty much what you need. If you want to compare the elements using regular expressions, try preg_grep, but you will need to prepare the pattern first.



Related Topics



Leave a reply



Submit