Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find all intersections between two arrays of objects in javascript React?

I have two arrays of objects. The Arrays can be of any length. For example my first array "details" consists of three objects,

let details = [
{a: 1, b: 200, name: "dad"}, 
{a:2, b: 250, name: "cat"}, 
{a:3, b: 212, name: "dog" } 
] 

second array consists of four objects:

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" }
] 

How to obtain an array that consists of all intersections by some property of object, for example by 'b' ?

I mean I want to obtain filtered array from "certs" array, that will contain only three objects not four.

Because element at index 1 in certs array has property "b" which equals to 251. But "details" array doesn't have object with property b equals to 251.

So my filtered certs array should consists of only three objects. How to implement this?

I tried lodash methods, but none of them fit. For example:

_.intersectionBy(certs, details, 'b')

gives me only this:

0: {id: 991, b: 250, dn: "qwerty", sign: "GOST"}
1: {id: 957, b: 212, dn: "how you", sign: "black"}
length: 2

This object doesnt exist in final array:

{id: 100, b: 250, dn: "how are", sign: "twofish" }
like image 840
Dragon14 Avatar asked Nov 07 '22 14:11

Dragon14


1 Answers

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)
like image 137
Moe007 Avatar answered Nov 14 '22 21:11

Moe007