【问题标题】:How to intersect two arrays and keep the key如何使两个数组相交并保留密钥
【发布时间】:2018-05-29 12:29:09
【问题描述】:

在 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] => 红色)

如您所见,它保留了 a0 的密钥。

我知道 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 创建,因为我认为语法更简洁。

【问题讨论】:

  • 数组值为黄金。赞成。
  • ['my', 'life', 'sucks', 'so', 'hard'] === true

标签: javascript php arrays ecmascript-6


【解决方案1】:

Array#reduce试试这个解决方案

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

【讨论】:

    【解决方案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);

    【讨论】:

      猜你喜欢
      • 2018-01-08
      • 1970-01-01
      • 2014-02-01
      • 2013-01-25
      • 1970-01-01
      • 2014-05-08
      • 2020-09-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多