Consider the following array:
const array = [{
typeName: 'welcome', orientation: 'landscape', languageId: 1, value: 'Welcome'
}, {
typeName: 'welcome', orientation: 'landscape', languageId: 2, value: 'Bonjour'
}, {
typeName: 'welcome', orientation: 'portrait', languageId: 2, value: 'Bonjour bonjour'
}]
The desired output should be:
{
welcome: {
landscape: ['Welcome'],
portrait: ['Bonjour bonjour']
}
}
To achieve this, we need to convert the array into an object structure like
{typeName: {orientation: value[]}}
, as shown below:
// This is NOT the final output, it's an intermediate step -- keep reading
{
welcome: {
landscape: ['Welcome', 'Bonjour'],
portrait: ['Bonjour bonjour']
}
}
However, there is a requirement for prioritization: if languageId=1 is present in the array, then ignore all other values with the same typeName and orientation. In the given example, only ['Welcome'] should be included since its languageId is 1, meaning 'Bonjour' can be ignored. If languageId=1 is missing, any value can be added (in this case, welcome.portrait).
The conversion process is straightforward using the .reduce() method as demonstrated by the code snippet provided.
However, dealing with prioritization while avoiding nested loops poses a challenge. The current solution involves filtering the array with an inner loop to check for conflicting types. While this works without issues, it may impact performance when handling large arrays.
Therefore, the main question remains: what is the most efficient approach to eliminate the need for inner loops?