Difference and intersection of two arrays containing objects
This is the solution that worked for me.
var intersect = function (arr1, arr2) {
var intersect = [];
_.each(arr1, function (a) {
_.each(arr2, function (b) {
if (compare(a, b))
intersect.push(a);
});
});
return intersect;
};
var unintersect = function (arr1, arr2) {
var unintersect = [];
_.each(arr1, function (a) {
var found = false;
_.each(arr2, function (b) {
if (compare(a, b)) {
found = true;
}
});
if (!found) {
unintersect.push(a);
}
});
return unintersect;
};
function compare(a, b) {
if (a.userId === b.userId)
return true;
else return false;
}
Intersection of values of 2 arrays of objects
var kiran = [];
var array1 = [{ key1: 'value1' }, { key1: 'value2' }];
var array2 = [{ key2: 'value0' }, { key2: 'value2' }];
array1.map(function(item1){
array2.map(function(item2){
if(item1.key1 === item2.key2){
kiran.push(item2.key2);
}
})
})
console.log(kiran);
intersection of objects except for one attribute between two arrays
You could take a simplified approach and omit foot
property and get the intersection by _.isEqual
for the lefot over properties.
var a = [{ weight: '75', height: '170', foot: 'Left', available: true }, { weight: '88', height: '190', foot: 'Right', available: true }, { weight: '65', height: '163', foot: 'Right', available: false }, { weight: '70', height: '168', foot: 'Left', available: true }], b = [{ weight: '75', height: '170', foot: '', available: true }, { weight: '93', height: '201', foot: '', available: true }, { weight: '65', height: '163', foot: '', available: false }], omitFoot = o => _.omit(o, 'foot'), intersection = _.intersectionWith( _.map(a, omitFoot), _.map(b, omitFoot), _.isEqual );
console.log(intersection);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>
How to get the difference between two arrays in JavaScript?
This answer was written in 2009, so it is a bit outdated, also it's rather educational for understanding the problem. Best solution I'd use today would be
let difference = arr1.filter(x => !arr2.includes(x));
(credits to other author here)
I assume you are comparing a normal array. If not, you need to change the for loop to a for .. in loop.
function arr_diff (a1, a2) {
var a = [], diff = [];
for (var i = 0; i < a1.length; i++) {
a[a1[i]] = true;
}
for (var i = 0; i < a2.length; i++) {
if (a[a2[i]]) {
delete a[a2[i]];
} else {
a[a2[i]] = true;
}
}
for (var k in a) {
diff.push(k);
}
return diff;
}
console.log(arr_diff(['a', 'b'], ['a', 'b', 'c', 'd']));
console.log(arr_diff("abcd", "abcde"));
console.log(arr_diff("zxc", "zxc"));
How to find all intersections between two arrays of objects in javascript React?
Simply use the filter() method twice:
let details = [ {a: 1, b: 200, name: "dad"}, {a:2, b: 250, name: "cat"}, {a:3, b: 212, name: "dog" } ]
let certs = [ {id: 991, b: 250, dn: "qwerty", sign: "GOST"}, {id: 950, b: 251, dn: "how", sign: "RSA" }, {id: 100, b: 250, dn: "how are", sign: "twofish" }, {id: 957, b: 212, dn: "how you", sign: "black" }]
const result = certs.filter(cert => { let arr = details.filter(detail => detail.b === cert.b) return !(arr.length === 0)});
console.log(result)
Simplest code for array intersection in javascript
Use a combination of Array.prototype.filter
and Array.prototype.includes
:
const filteredArray = array1.filter(value => array2.includes(value));
For older browsers, with Array.prototype.indexOf
and without an arrow function:
var filteredArray = array1.filter(function(n) {
return array2.indexOf(n) !== -1;
});
NB! Both .includes
and .indexOf
internally compares elements in the array by using ===
, so if the array contains objects it will only compare object references (not their content). If you want to specify your own comparison logic, use Array.prototype.some
instead.
php intersection of array of slightly different objects
You are not looking for the same objects as you have different types here, namely object1 and object2.
Instead you're looking for similiar objects in which you're looking for those which are same for customer-ID and order-ID.
This is important to note, as by only that you can say that the comparison does not belong into any of these two types, because you could place the comparison into both, object1 and object2.
In such a case where you can not clearly identify to which object type a functionality belongs to, a good rule of thumb is to place it between these objects, e.g. create a function or a new type of it's own for the operation itself.
That for a design decision.
Now about how to make such comparison of different objects easy? One way to do that is with a hash function.
Assuming that these two IDs are integers, you can create a hash for each of these different objects with a hash function:
function customer_order_hash($object) {
return sprintf('%d/%d', $object->getCustomerId(), $object->getOrderId());
}
This hash now makes it easy to identify objects that are the same or not: The hash will be the same.
You then can make use of it, e.g. getting all objects from $array1
that have corresponding objects in $array2
:
function compare_objects($a, $b) {
return strcmp(customer_order_hash($a), customer_order_hash($b));
}
$result = array_uintersect($array1, $array2, 'compare_objects');
The result then contains only these objects from the first array that were found as well by such a comparison within the second array.
As you can see, there is no (written) loop at all. Just one hash function and one comparison function making use of it.
An object hash function normally works well for such comparisons (same or not). It can also work for sorting, however this example is not working for sorting.
Additional info: A built-in object hash function in PHP is spl_object_hash
.
How to find all OBJECTS that intersect two arrays?
You can flatten the objects using JSON.stringify()
and then check for intersection.
var a1 = [{"a":"b"}, {"b":"c"}, {"d":"e"}],
a2 = [{"g":"h"}, {"a":"b"}, {"i":"j"}]
// flatten objects in second array
var stringifiedA2 = a2.map(function(x) {
return JSON.stringify(x);
});
// get intersecting objects
var intersecting = a1.filter(function(x) {
return stringifiedA2.indexOf(JSON.stringify(x)) !== -1;
});
intersecting
will contain the object {"a": "b"}
Return object after performing intersection of two arrays based on attribute
you can:
1 :
override the eql?(other)
method then the array intersection will work
class Link < ApplicationRecord
def eql?(other)
self.class == other.class && self.id == other&.id # classes comparing class is a guard here
end
# you should always update the hash if you are overriding the eql?() https://stackoverflow.com/a/54961965/5872935
def hash
self.id.hash
end
end
2:
use array.select
:
array_links.flat_map {|i| selected_links.select {|k| k.user_id == i.user_id }}
Related Topics
Facebook How to Check If User Has Liked Page and Show Content
Plain Count Up Timer in JavaScript
How to Perform an Http File Upload Using Express on Cloud Functions for Firebase (Multer, Busboy)
JavaScript Settimeout() Won't Wait to Execute
How to Get the Current Time Only in JavaScript
Injecting a Mock into an Angularjs Service
How to Understand Usecapture Parameter in Addeventlistener
Access-Control-Allow-Origin Denied Spotify API
Why Does an Onclick Property Set with Setattribute Fail to Work in Ie
How to Set State of Response from Axios in React
Prototype: Deep Scope of "This" to Access Instance's Scope
Canvas Todataurl() Returns Blank Image
Typescript Type 'String' Is Not Assignable to Type