function splitIntoCustomsDeclarations(data) {
const result = [];
const groupedByLicense = {};
const withLicense = data.filter(item => item.importLicense);
const withoutLicense = data.filter(item => !item.importLicense);
withLicense.forEach(item => {
const license = item.importLicense || 'NO_LICENSE';
if (!groupedByLicense[license]) {
groupedByLicense[license] = [];
}
groupedByLicense[license].push(item);
});
const licenseKeys = Object.keys(groupedByLicense);
if (licenseKeys.length > 0) {
const lastKey = licenseKeys[licenseKeys.length - 1];
groupedByLicense[lastKey].push(...withoutLicense);
} else {
groupedByLicense["No License"] = withoutLicense;
}
for (const license in groupedByLicense) {
const itemsByLicense = groupedByLicense[license];
const withExclusion = {};
const withoutExclusion = [];
itemsByLicense.forEach(item => {
const exclusionNumber = item.usExclusionNumber;
if (exclusionNumber) {
if (!withExclusion[exclusionNumber]) {
withExclusion[exclusionNumber] = [];
}
withExclusion[exclusionNumber].push(item);
} else {
withoutExclusion.push(item);
}
});
for (const exclusionNumber in withExclusion) {
result.push(withExclusion[exclusionNumber]);
}
if (withoutExclusion.length > 0) {
result.push(withoutExclusion);
}
}
return result;
}
const data = [
{ importLicense: 'LIC001', usExclusionNumber: 'EXC001', description: 'Item 1' },
{ importLicense: 'LIC001', usExclusionNumber: 'EXC002', description: 'Item 2' },
{ importLicense: 'LIC002', usExclusionNumber: 'EXC001', description: 'Item 3' },
{ importLicense: 'LIC002', usExclusionNumber: null, description: 'Item 4' },
{ importLicense: 'LIC001', usExclusionNumber: null, description: 'Item 5' },
{ importLicense: null, usExclusionNumber: null, description: 'Item 6' },
{ importLicense: null, usExclusionNumber: 'EXC003', description: 'Item 7' }
];
const splitData = splitIntoCustomsDeclarations(data);
console.log(splitData);