在 PHP 中,我们有一个名为 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.
所以它会是这样的:
<?php
$array1 = array("a" => "green", "red", "blue");
$array2 = array("b" => "green", "yellow", "red");
$result = array_intersect($array1, $array2);
print_r($result);
输出:
Array ( [a] => green [0] => red )
如您所见,它保留了键 a
和 0
。
我知道 JavaScript 中的数组与 PHP 不同,但它们类似于 JavaScript 中的对象。
假设我有这样的输入:
let a = ['my', 'life', 'sucks', 'so', 'hard'];
let b = ['life', 'sucks', 'hard'];
我希望这会导致这样的结果:
let r = { 1: 'life', 2: 'sucks', 4: 'hard' }
在 resume 中,keys 是找到它的索引(位置)。
我看到一个用 ES6 创建的方法是这样的:
const intersect = (leftArray, rightArray) => leftArray.filter(value => rightArray.indexOf(value) > -1);
但同样,它不会只返回已找到的值的键。
如果也可以使用 ES6 创建,因为我认为语法更清晰。
最佳答案
你可以使用 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);
关于javascript - 如何相交两个数组并保留 key ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47829910/