# javascript – get max/min of multiple subarrays

###### Asked By: Anonymous

Say below data structure:

``````var data = [
{
name: "USA",
values: [
{date: "2008", price: "20"},
{date: "2009", price: "30"}
]
},
{
values: [
{date: "2000", price: "40"},
{date: "2001", price: "50"}
]
},
{
name: "Maxico",
values: [
{date: "2006", price: "60"},
{date: "2007", price: "70"}
]
}
];
``````

I would like to get the min/max of all price field in multiple subarrays, the arrays number currently is 3 but it maybe changed.

The function minmax(data) should output ["20","70"] for this sample!

## Solution

###### Answered By: Anonymous

Write a `prices` traversal and a generic `minmax` method

_x000D_

_x000D_

``````function* prices(t) {
switch (t?.constructor) {
case Array:
for (const v of t)
yield *prices(v)
break
case Object:
if (t?.values)
yield *prices(t.values)
else
yield t?.price
break
}
}

function minmax(t) {
let min = Infinity
let max = -Infinity
for (const v of t) {
min = Math.min(min, v)
max = Math.max(max, v)
}
return {min, max}
}

const data =
[{name: "USA",values: [{date: "2008", price: "20"},{date: "2009", price: "30"}]},{name: "Canada",values: [{date: "2000", price: "40"},{date: "2001", price: "50"}]},{name: "Maxico",values: [{date: "2006", price: "60"},{date: "2007", price: "70"}]}];

console.log(minmax(prices(data)))
// { min: 20, max: 70 }

console.log(minmax([]))
// { min: Infinity, max: -Infinity }``````

_x000D_

_x000D_

x000D

﻿