如何求两个数组的交集并保留键值

4
在PHP中,我们有一个叫做array_intersect的方法:

array_intersect()返回一个包含所有在参数中都存在于数组1中的值的数组。请注意,键被保留。

因此,它可能是这样的:
<?php
$array1 = array("a" => "green", "red", "blue");
$array2 = array("b" => "green", "yellow", "red");
$result = array_intersect($array1, $array2);
print_r($result);

输出结果:

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

正如您所看到的,它保留了键a0

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

想象一下我有这个输入:

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

我希望得到以下类似的结果:

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

简而言之,键将是它被找到的索引(位置)。

我看到了一个使用 ES6 创建的方法,大致如下:

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

但是,它仅返回已找到的值,而不是键。

如果可能的话,也可以使用ES6创建,因为我认为语法更加简洁。


2
数组值很棒。已点赞。 - David
3
我的生活非常糟糕。 - Panos Kalatzantonakis
2个回答

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


1
尝试使用 Array#reduce 这个解决方案。保留html,不做解释。

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接