I am trying to combine two Javascript arrays into one array with straight Javascript.
I am trying to accomplish exactly what has been asked in the below 2 questions. However, my data has several points that need to be combine rather than a single item; and the arrays have a common element between them that is exactly the same.
Here are the other questions:
Here is my code (which is from the last answer provided by the first question listed above)(but is obviously wrong):
let arr1 = [
{ route: 'x1' },
{ route: 'x2' },
{ route: 'x3' },
{ route: 'x4' },
{ route: 'x5' }
]
let arr2 = [
{ pattern: 'y1', route: 'x1' },
{ pattern: 'y2', route: 'x1' },
{ pattern: 'y3', route: 'x2' },
{ pattern: 'y4', route: 'x2' },
{ pattern: 'y5', route: 'x3' },
{ pattern: 'y6', route: 'x3' },
{ pattern: 'y7', route: 'x4' },
{ pattern: 'y8', route: 'x4' },
{ pattern: 'y9', route: 'x5' },
{ pattern: 'y10', route: 'x5' }
]
let finalArray2 = [];
arr2.forEach(member => {
finalArray2.push(Object.assign({}, member,
{ route: arr1.find(m => m.route === member.route).route }
))
});
console.log(finalArray2);
I really need results to look like the following:
let arr3 = [
{ route: 'x1', pattern: ['y1','y2'] },
{ route: 'x2', pattern: ['y3','y4'] },
{ route: 'x3', pattern: ['y5','y6'] },
{ route: 'x4', pattern: ['y7','y8'] },
{ route: 'x5', pattern: ['y9','y10'] }
]
So that it can be presented in a table like the following:
<style type="text/css">
.tg {border-collapse:collapse;border-spacing:0;}
.tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;}
.tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;}
.tg .tg-yw4l{vertical-align:top}
</style>
<table class="tg">
<tr>
<th class="tg-yw4l">ROUTE</th>
<th class="tg-yw4l">PATTERN(s)</th>
</tr>
<tr>
<td class="tg-yw4l">x1</td>
<td class="tg-yw4l">y1, y2</td>
</tr>
<tr>
<td class="tg-yw4l">x2</td>
<td class="tg-yw4l">y3, y4</td>
</tr>
<tr>
<td class="tg-yw4l">x3</td>
<td class="tg-yw4l">y5, y6</td>
</tr>
<tr>
<td class="tg-yw4l">x4</td>
<td class="tg-yw4l">y7, y8</td>
</tr>
<tr>
<td class="tg-yw4l">x5</td>
<td class="tg-yw4l">y9, y10</td>
</tr>
</table>