I have 2 arrays, each is like a database table row set.
array1 = [ ['AB2C', 'Red', 113], ['BE4F', 'Green', 164], ['AE3G', 'Blue', 143], ] array2 = [ [143, 'FabricB2', 'W5'], [189, 'FabricC9', 'W4'], [113, 'FabricA3', ' W5'], [143, 'FabricD1', 'W6']]; I want to do a join and find matching rows, returning the matched rows in array2 along with the matched row in array1. The returned matching array should look like this:
[143, 'FabricB2', 'W5', 'AE3G', 'Blue', 143], [113, 'FabricA3', ' W5', 'AB2C', 'Red', 113], [143, 'FabricD1', 'W6', 'AE3G', 'Blue', 143] I tried to use JavaScript methods map(), filter(), flatMap(), spread operator but can't get the result. Anyone can help me with this? With the shortest code? The one I have below does not work.
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); } Does not give the expected result which is this
[143, 'FabricB2', 'W5', 'AE3G', 'Blue', 143], [113, 'FabricA3', ' W5', 'AB2C', 'Red', 113], [143, 'FabricD1', 'W6', 'AE3G', 'Blue', 143] Gives this which is not what I want
Info [ [ [ 113, 'FabricA3', ' W5' ], 'AB2C', 'Red', 113 ], [ 'BE4F', 'Green', 164 ], [ [ 143, 'FabricB2', 'W5' ], [ 143, 'FabricD1', 'W6' ], 'AE3G', 'Blue', 143 ] ]