EN
TypeScript - Array reduce() method example
11
points
In TypeScript it is possible to convert array using reduce method in following ways.
1. Array
conversion example
let array = [
{
id : 1,
group : 'Juices',
items : [
{ name : 'Apple', price : 1.4 },
{ name : 'Orange', price : 1.7 }
]
},
{
id : 2,
group : 'Baking',
items : [
{ name : 'Bread', price : 1.3 },
{ name : 'Roll', price : 0.5 },
{ name : 'Loaf', price : 1.1 }
]
},
{
id : 3,
group : 'Meat',
items : [
{ name : 'Salmon', price : 15.0 },
{ name : 'Turey', price : 6.5 },
{ name : 'Chicken', price : 7.8 }
]
},
];
let reduce = (array : Array<any>, entry : any, index : number) : Array<any> => {
[...array, ...entry.items];
};
let products = array.reduce(reduce, new Array<any>());
console.log(products);
Where:
array.reduce(reduce, new Array<any>())
method has been used to convert array of groups to array of items with initial empty array (secondreduce
method argument),let reduce = (array : Array<any>, entry : any) : Array<any> ...
method contains conversion and merging logic for each array element
where:array : Array<any>
variable indicates array returned during previous iteration ornew Array<any>()
object if it is first iteration,entry : any
variable contains currently iterated element,
Output (with NodeJS):
[
{ name: 'Apple', price: 1.4 },
{ name: 'Orange', price: 1.7 },
{ name: 'Bread', price: 1.3 },
{ name: 'Roll', price: 0.5 },
{ name: 'Loaf', price: 1.1 },
{ name: 'Salmon', price: 15 },
{ name: 'Turey', price: 6.5 },
{ name: 'Chicken', price: 7.8 }
]
2. Item finding example
let array = [
{
id : 1,
group : 'Juices',
items : [
{ name : 'Apple', price : 1.4 },
{ name : 'Orange', price : 1.7 }
]
},
{
id : 2,
group : 'Baking',
items : [
{ name : 'Bread', price : 1.3 },
{ name : 'Roll', price : 0.5 },
{ name : 'Loaf', price : 1.1 }
]
},
{
id : 3,
group : 'Meat',
items : [
{ name : 'Salmon', price : 15.0 },
{ name : 'Turey', price : 6.5 },
{ name : 'Chicken', price : 7.8 }
]
},
];
let reduce = (result : any, entry : any, index : number) : any => {
if(entry.items.length < result.items.length)
return entry;
return result;
};
let smallestGroup = array.reduce(reduce);
console.log(smallestGroup);
Output (with NodeJS):
{
id: 1,
group: 'Juices',
items: [
{ name: 'Apple', price: 1.4 },
{ name: 'Orange', price: 1.7 }
]
}