JavaScript 2D 数组并返回匹配行

问题描述 投票:0回答:2

我有2个数组,每个数组都像一个数据库表行集。

array1 = [
['AB2C', 'Red', 113],
['BE4F', 'Green', 164],
['AE3G', 'Blue', 143],
]

array2 = [
[143, 'FabricB2', 'W5'],
[189, 'FabricC9', 'W4'],
[113, 'FabricA3', ' W5'],
[143, 'FabricD1', 'W6']];

我想要进行连接并查找匹配行,返回 array2 中的匹配行以及 array1 中的匹配行。返回的匹配数组应该如下所示:

[143, 'FabricB2', 'W5',  'AE3G', 'Blue', 143],
[113, 'FabricA3', ' W5', 'AB2C', 'Red', 113],
[143, 'FabricD1', 'W6',  'AE3G', 'Blue', 143]

我尝试使用 JavaScript 方法 map()、filter()、flatMap()、spread 运算符,但无法得到结果。 任何人都可以帮我解决这个问题吗?用最短的代码?我下面的这个不起作用。

function testArrayFunction() {

array1 = [
['AB2C', 'Red', 113],
['BE4F', 'Green', 164],
['AE3G', 'Blue', 143],

];

array2 = [
[143, 'FabricB2', 'W5'],
[189, 'FabricC9', 'W4'],
[113, 'FabricA3', ' W5'],
[143, 'FabricD1', 'W6']];

var array1Element = 2;
var array2Element = 0;

var res = array1
.map(x => [  ...  array2
.filter(    y => y[array2Element] === x[array1Element ] )  ,...x ] );

console.log(res);

}

没有给出预期的结果,这就是这个

[143, 'FabricB2', 'W5', 'AE3G', 'Blue', 143],
[113, 'FabricA3', ' W5', 'AB2C', 'Red', 113],
[143, 'FabricD1', 'W6',  'AE3G', 'Blue', 143]

这不是我想要的

Info    
[ [ [ 113, 'FabricA3', ' W5' ], 'AB2C', 'Red', 113 ],
[ 'BE4F', 'Green', 164 ],
[ [ 143, 'FabricB2', 'W5' ],
[ 143, 'FabricD1', 'W6' ], 'AE3G', 'Blue', 143 ] ]
javascript arrays dictionary filter spread
2个回答
0
投票

我认为您使用

map
filter
走在正确的轨道上:

const array1 = [
  ['AB2C', 'Red', 113],
  ['BE4F', 'Green', 164],
  ['AE3G', 'Blue', 143],
]
const array2 = [
  [143, 'FabricB2', 'W5'],
  [189, 'FabricC9', 'W4'],
  [113, 'FabricA3', ' W5'],
  [143, 'FabricD1', 'W6']
];
const result = array2
  .map(row2 => {
    const match = array1.find(row1 => row1[2] === row2[0]);
    return match ? [...row2, ...match] : null;
  })
  .filter(row => row !== null);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }


0
投票

您可以将映射与查找结合起来构建一个新数组:

let array1 = [
['AB2C', 'Red', 113],
['BE4F', 'Green', 164],
['AE3G', 'Blue', 143],
]

let array2 = [
[143, 'FabricB2', 'W5'],
[189, 'FabricC9', 'W4'],
[113, 'FabricA3', ' W5'],
[143, 'FabricD1', 'W6']];


let result = array1.map(entry => {
  // Find in array 2
  let match = array2.find(search => search[0] === entry[2])
  if (match) {
    return [...new Set([...entry, ...match])]
  } else {
  return entry
  }

})

console.log(result)

© www.soinside.com 2019 - 2024. All rights reserved.