Как-то так:
interface IOrder {
date: string,
docTypesName: string,
docId: number,
image: string,
name: string,
price: number,
quantity: number,
removed: number,
}
interface IProduct {
image: string,
name: string,
price: number,
quantity: number,
}
interface IDocument {
date: string,
docId: number,
docTypesName: string,
products: IProduct[],
}
interface IElement {
date: string,
documents: IDocument[]
}
interface IElementMap {
date: string,
documents: Record<string, IDocument>
}
type IResultMap = Record<string, IElementMap>;
function f(orders: IOrder[]): IElement[] {
const result = orders.reduce((accumulator, currentValue) => {
const date = currentValue.date.split(' ')[0];
if (!accumulator[date]) {
accumulator[date] = {
date,
documents: {},
}
}
if (!accumulator[date].documents[currentValue.docTypesName]) {
accumulator[date].documents[currentValue.docTypesName] = {
date: currentValue.date,
docId: currentValue.docId,
docTypesName: currentValue.docTypesName,
products: [],
}
}
accumulator[date].documents[currentValue.docTypesName].products.push({
name: currentValue.name,
price: currentValue.price,
image: currentValue.image,
quantity: currentValue.quantity,
})
return accumulator;
}, {} as IResultMap)
console.log('result', result);
return Object.values(result).map(currentValue => {
console.log('currentValue', currentValue);
return {
...currentValue,
documents: Object.values(currentValue.documents)
}
});
}
console.log(f(orders));