如何交叉两个数组并保持密钥(How to intersect two arrays and keep the key)

在PHP中,我们有一个名为array_intersect的方法:

array_intersect()返回一个数组,其中包含所有参数中存在的array1的所有值。 请注意,密钥保留。

所以它会是这样的:

<?php $array1 = array("a" => "green", "red", "blue"); $array2 = array("b" => "green", "yellow", "red"); $result = array_intersect($array1, $array2); print_r($result);

输出:

数组([a] =>绿色[0] =>红色)

如你所见,它保持键a和0 。

我知道JavaScript中的数组与PHP不同,但它们与JavaScript中的对象类似。

想象一下,我有这个输入:

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

我希望这会产生这样的结果:

让r = {1:'生活',2:'糟透了',4:'硬'}

在简历中,键将是找到它的索引(位置)。

我看到了一个用ES6创建的方法,它是这样的:

const intersect = (leftArray, rightArray) => leftArray.filter(value => rightArray.indexOf(value) > -1);

但同样,它不会仅返回已找到的值的键。

如果可以使用ES6创建,因为我认为语法更清晰。

In PHP we have a method called array_intersect:

array_intersect() returns an array containing all the values of array1 that are present in all the arguments. Note that keys are preserved.

So it would 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);

The output:

Array ( [a] => green [0] => red )

As you can see it keeps the keys a and 0.

I know that arrays in JavaScript is different from PHP but they are similar to an object in JavaScript.

Imagine that I have this input:

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

I wanted this to result in something like this:

let r = { 1: 'life', 2: 'sucks', 4: 'hard' }

In resume, the keys would be the index (position) that it has been found.

I saw a method that was created with ES6 that is something like this:

const intersect = (leftArray, rightArray) => leftArray.filter(value => rightArray.indexOf(value) > -1);

But again, it won't return the keys only the value that has been found.

And if is possible to create using ES6 as well cause I think that the syntax is much cleaner.

最满意答案

您可以使用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); 
  
 

You could use Object.assign and map the wanted properties.

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); 
  
 

更多推荐