Seeking assistance with a programming task that is straightforward yet challenging for me.
There are two arrays: one long and one short.
var arrayShort = [
{
id: 'A',
name: 'first'
},{
id: 'B',
name: 'second'
},{
id: 'C',
name: 'third'
}
]
var arrayLong = [
{
id: 'A',
name: 'firstSub1'
},{
id: 'A',
name: 'firstSub2'
},{
id: 'A',
name: 'firstSub3'
},{
id: 'B',
name: 'secondSub1'
},{
id: 'B',
name: 'secondSub2'
},{
id: 'B',
name: 'secondSub3'
},{
id: 'C',
name: 'thirdSub1'
},{
id: 'C',
name: 'thirdSub2'
},{
id: 'C',
name: 'thirdSub3'
}
]
Looking to merge them based on shared ids, resulting in:
var arrayCombined = [
{
id: 'A',
name: 'first'
},{
id: 'A',
name: 'firstSub1'
},{
id: 'A',
name: 'firstSub2'
},{
id: 'A',
name: 'firstSub3'
},{
id: 'B',
name: 'second'
},{
id: 'B',
name: 'secondSub1'
},{
id: 'B',
name: 'secondSub2'
},{
id: 'B',
name: 'secondSub3'
},{
id: 'C',
name: 'third'
},{
id: 'C',
name: 'thirdSub1'
},{
id: 'C',
name: 'thirdSub2'
},{
id: 'C',
name: 'thirdSub3'
},
]
Essential
Sequential order matters.
My Attempts
for (var i = 0; i < arrayShort.length; i++) {
var itemShort = arrayShort[i]
console.log(itemShort)
for (var j = 0; j < arrayLong.length; j++) {
var itemLong = arrayLong[j]
if (itemLong.id === itemShort.id) {
console.log(itemLong)
arrayShort.splice(j + 1, 0, arrayLong)
}
}
}
var arrayCombined = arrayShort
console.log(arrayCombined)
This code leads to an infinite loop without clear reasons. I am aware of the risks associated with nested loops and conditions.
Thinking about better approaches mentally or with code?
Codepen link, access dev tools for details
Remarks:
- Preference for Vanilla JavaScript solutions, although options with Lodash or Underscore are welcome. These libraries could simplify the process, but understanding their usage challenges me.
- Struggling with appropriate search terms for this task...any suggestions?
Appreciate any feedback/recommendations.