How to cross two arrays and save the key

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 aand 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, , .

+4
2

Object.assign .

var a = ['my', 'life', 'sucks', 'so', 'hard'],
    b = ['life', 'sucks', 'hard'],
    result = Object.assign(...a.map((v, i) => b.includes(v) && { [i]: v }));
    
console.log(result);
Hide result
+3

let a = ['your', 'life', 'sucks', 'so', 'hard'];
let b = ['life', 'sucks', 'hard'];

let r = a.reduce((obj, item, index) => {

  if(b.includes(item)) {
     obj[index] = item;
  }
  
  return obj;
}, {});

console.log(r);
Hide result
+1

Source: https://habr.com/ru/post/1690850/


All Articles