EN
TypeScript - Array reduce() method example
11 points
In TypeScript it is possible to convert array using reduce method in following ways.
xxxxxxxxxx
1
let array = [
2
{
3
id : 1,
4
group : 'Juices',
5
items : [
6
{ name : 'Apple', price : 1.4 },
7
{ name : 'Orange', price : 1.7 }
8
]
9
},
10
{
11
id : 2,
12
group : 'Baking',
13
items : [
14
{ name : 'Bread', price : 1.3 },
15
{ name : 'Roll', price : 0.5 },
16
{ name : 'Loaf', price : 1.1 }
17
]
18
},
19
{
20
id : 3,
21
group : 'Meat',
22
items : [
23
{ name : 'Salmon', price : 15.0 },
24
{ name : 'Turey', price : 6.5 },
25
{ name : 'Chicken', price : 7.8 }
26
]
27
},
28
];
29
30
let reduce = (array : Array<any>, entry : any, index : number) : Array<any> => {
31
[array, entry.items];
32
};
33
34
let products = array.reduce(reduce, new Array<any>());
35
36
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):
xxxxxxxxxx
1
[
2
{ name: 'Apple', price: 1.4 },
3
{ name: 'Orange', price: 1.7 },
4
{ name: 'Bread', price: 1.3 },
5
{ name: 'Roll', price: 0.5 },
6
{ name: 'Loaf', price: 1.1 },
7
{ name: 'Salmon', price: 15 },
8
{ name: 'Turey', price: 6.5 },
9
{ name: 'Chicken', price: 7.8 }
10
]
xxxxxxxxxx
1
let array = [
2
{
3
id : 1,
4
group : 'Juices',
5
items : [
6
{ name : 'Apple', price : 1.4 },
7
{ name : 'Orange', price : 1.7 }
8
]
9
},
10
{
11
id : 2,
12
group : 'Baking',
13
items : [
14
{ name : 'Bread', price : 1.3 },
15
{ name : 'Roll', price : 0.5 },
16
{ name : 'Loaf', price : 1.1 }
17
]
18
},
19
{
20
id : 3,
21
group : 'Meat',
22
items : [
23
{ name : 'Salmon', price : 15.0 },
24
{ name : 'Turey', price : 6.5 },
25
{ name : 'Chicken', price : 7.8 }
26
]
27
},
28
];
29
30
let reduce = (result : any, entry : any, index : number) : any => {
31
if(entry.items.length < result.items.length)
32
return entry;
33
34
return result;
35
};
36
37
let smallestGroup = array.reduce(reduce);
38
39
console.log(smallestGroup);
Output (with NodeJS):
xxxxxxxxxx
1
{
2
id: 1,
3
group: 'Juices',
4
items: [
5
{ name: 'Apple', price: 1.4 },
6
{ name: 'Orange', price: 1.7 }
7
]
8
}