In PHP, we have a method called array_intersect
:
array_intersect () returns an array containing all array1 values that are present in all arguments. Please note that keys are saved.
So, it will be something like this:
<?php
$array1 = array("a" => "green", "red", "blue");
$array2 = array("b" => "green", "yellow", "red");
$result = array_intersect($array1, $array2);
print_r($result);
Output:
Array ([a] => green [0] => red)
As you can see, the keys a
and are stored in it 0
.
I know that arrays in JavaScript are different from PHP, but they look like an object in JavaScript.
Imagine I have this input:
let a = ['my', 'life', 'sucks', 'so', 'hard'];
let b = ['life', 'sucks', 'hard'];
I wanted this to lead to something like this:
let r = {1: 'life', 2: 'sucks', 4: 'hard'}
In summary, the keys will be the index (position) that was found.
I saw a method that was created with ES6, something like this:
const intersect = (leftArray, rightArray) => leftArray.filter(value => rightArray.indexOf(value) > -1);
, .
ES6, , .