I have an array consisting of various objects
const allRecords = [
{
type: 'fruit',
name: 'apple'
},
{
type: 'vegetable',
name: 'celery'
},
{
type: 'meat',
name: 'chicken'
}
]
My goal is to merge objects from another array next to similar type elements.
const newRecords = [
{
type: 'fruit',
name: 'pear'
},
{
type: 'vegetable',
name: 'spinach'
},
{
type: 'meat',
name: 'pork'
}
]
For instance, calling this function:
allRecords.sortAndInsert(newRecords)
Should yield a result as follows:
[
{
type: 'fruit',
name: 'apple'
},
{
type: 'fruit',
name: 'pear'
},
{
type: 'vegetable',
name: 'celery'
},
{
type: 'vegetable',
name: 'spinach'
},
{
type: 'meat',
name: 'chicken'
},
{
type: 'meat',
name: 'pork'
},
With my current code, I determine the position by calculating the length of arrays:
// Calculate record amount per group.
//In our example, it will be 2 for each group - 'apple' and 'pear', etc.
const multiplier = (allRecords.length + newRecords.length) /
(newRecords.length);
for (let i = 0; i < newRecords.length; i++){
// Insert record at 1 + i + multiplier. 'pear' should go to 1 with 0 * 2 = 1
allRecords.splice(1 + i * multiplier, 0, newRecords[i]);
}
return allRecords;
However, this method lacks readability and assumes each group has only one item of each type.
My ideal solution would group items based on properties and sort them accordingly in a specific order (e.g., 'fruit' first, followed by 'vegetable' then 'meat').