cancel
Showing results for 
Search instead for 
Did you mean: 

An element in an array is present in another array or not

lake
New Contributor

I would like to know how to check whether an element in one array is present in another array or not?
I have tried arr1.every(item => arr2.includes(item)) in mapper snap. It complaints about list type does not have a method named every. I used sl.ensureArray function to ensure (arr1 and arr2) as arrays.

1 ACCEPTED SOLUTION

Aleksandar_A
Contributor III

Hello @lake,

You can iterate through one of the arrays using either map or filter (depends on what you want as an output) and check if the current element is present in the second array.

Example input:

[
	{
		"arr1": [
			1,
			2,
			3,
			4,
			5,
			6
		],
		"arr2": [
			3,
			4,
			5,
			6,
			7,
			8
		]
	}
]

Using map:

$arr1.map(x => {"elem": x,"found": $arr2.indexOf(x) != -1})
"compare": [
			{
				"elem": 1,
				"found": false
			},
			{
				"elem": 2,
				"found": false
			},
			{
				"elem": 3,
				"found": true
			},
			{
				"elem": 4,
				"found": true
			},
			{
				"elem": 5,
				"found": true
			},
			{
				"elem": 6,
				"found": true
			}

Using filter:

$arr1.filter(x => $arr2.indexOf(x) != -1)
"present": [
			3,
			4,
			5,
			6
		]

You can refer to the attached pipeline and let me know if it helps you.

Regards,

Aleksandar.

 

View solution in original post

1 REPLY 1

Aleksandar_A
Contributor III

Hello @lake,

You can iterate through one of the arrays using either map or filter (depends on what you want as an output) and check if the current element is present in the second array.

Example input:

[
	{
		"arr1": [
			1,
			2,
			3,
			4,
			5,
			6
		],
		"arr2": [
			3,
			4,
			5,
			6,
			7,
			8
		]
	}
]

Using map:

$arr1.map(x => {"elem": x,"found": $arr2.indexOf(x) != -1})
"compare": [
			{
				"elem": 1,
				"found": false
			},
			{
				"elem": 2,
				"found": false
			},
			{
				"elem": 3,
				"found": true
			},
			{
				"elem": 4,
				"found": true
			},
			{
				"elem": 5,
				"found": true
			},
			{
				"elem": 6,
				"found": true
			}

Using filter:

$arr1.filter(x => $arr2.indexOf(x) != -1)
"present": [
			3,
			4,
			5,
			6
		]

You can refer to the attached pipeline and let me know if it helps you.

Regards,

Aleksandar.