好吧,通过使用一些数组魔法,我自己做了一个版本:
const satellitesData = getSatellitesData();
const feeds = [].concat.apply([], satellitesData.map(s => s.data));
// Extracting what you want...
const satellitesCount = satellitesData.length;
const feedsCount = feeds.length;
const mostObservantFeed = feeds.reduce((a, b) => (a.data.length > b.data.length) ? a : b);
console.table([{
'Satellites count': satellitesCount,
'Feeds count': feedsCount,
'Most observant feed': mostObservantFeed.label
}]);
// Your data, which will be retrieved from somewhere...
function getSatellitesData() {
return [
{
group: 'satellite-1',
data: [
{
label: 'feed-1a',
data: [
{
timeRange: [800, 820],
val: 'TargetC'
},
{
timeRange: [800, 820],
val: 'TargetD'
},
{
timeRange: [820, 840],
val: 'TargetA'
},
{
timeRange: [820, 840],
val: 'TargetC'
},
{
timeRange: [820, 840],
val: 'TargetD'
},
{
timeRange: [820, 840],
val: 'TargetB'
}
]
},
{
label: 'feed-2a',
data: [
{
timeRange: [780, 800],
val: 'TargetB'
}]
}
]
},
{
group: 'satellite-4',
data: [
{
label: 'feed-1b',
data: [
{
timeRange: [780, 800],
val: 'TargetA'
},
{
timeRange: [800, 820],
val: 'TargetB'
},
{
timeRange: [800, 820],
val: 'TargetC'
}
]
},
{
label: 'feed-2b',
data: [
{
timeRange: [780, 800],
val: 'TargetB'
}]
}
]
}
];
}
评论版
// For the sake of clarity, I just extracted the example data to
// a separate function...
const satellitesData = getSatellitesData();
/*
As the items of the original satellitesData array were objects, I needed to
simplify them, by making a `map` first. So, instead of an array of objects
whose items had an array property each one ("data"), after doing the map,
I'll have simply an array of arrays.
To make it even simpler, I use `[].concat.apply([], someArrayHere)`
to flatten our bidimensional array.
In the end, by using this trick, I create a flat array of feeds.
*/
const feeds = [].concat.apply([], satellitesData.map(s => s.data));
const satellitesCount = satellitesData.length;
// As I have an array of feeds above, it's just a question of getting
// the array length in order to find the feeds count
const feedsCount = feeds.length;
// Now I'm using reduce to iterate over the feeds. In each iteration,
// I'm comparing the targets count, to find the feed with more targets.
// At the end, the reduce will return the most observant feed.
const mostObservantFeed = feeds.reduce((a, b) => (a.data.length > b.data.length) ? a : b);
// To finish, console.table is just a fancy way of showing the data in the console. =)
console.table([{
'Satellites count': satellitesCount,
'Feeds count': feedsCount,
'Most observant feed': mostObservantFeed.label
}]);