本文整理汇总了TypeScript中lodash.groupBy函数的典型用法代码示例。如果您正苦于以下问题:TypeScript groupBy函数的具体用法?TypeScript groupBy怎么用?TypeScript groupBy使用的例子?那么, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了groupBy函数的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。
示例1: groupBy
export const searchByFilters = (
items = [],
filters = [],
returnDefaultHidden = false,
queryFields = ['name', 'desc']
) => {
const prefilteredItems = !returnDefaultHidden ? items.filter(({defaultHidden}) => !defaultHidden) : items;
const groupedFilters = groupBy(filters, 'relatedField');
if (!filters.length) {
return prefilteredItems;
}
return prefilteredItems.filter((item) => {
const filteringResults: any = map(groupedFilters, (selectedFilters: any) => {
const filterType = get(selectedFilters[0], 'type', DATA_TYPES.UNDEFINED);
switch (filterType) {
case DATA_TYPES.UNDEFINED:
return selectedFilters.some((filter) => {
const filterValue =
isArray(item[filter.relatedField]) && !item[filter.relatedField].length ? [''] : item[filter.relatedField];
const itemValue = isArray(filterValue) ? filterValue || [''] : [filterValue];
return itemValue.every((value) => {
if (typeof value === 'string') {
return !filter.value.value ? filter.value.value === value : compareStrings(value, filter.value.value);
}
if (typeof value === 'number') {
return value === filter.value.value;
}
return false;
});
});
break;
case DATA_TYPES.QUERY:
return selectedFilters.some((filter) => {
const logFound = item.comments && item.comments.length ? item.comments.some(({ comment }) => {
if (comment) {
return compareStrings(comment, filter.value.value);
}
return false;
}) : false;
return logFound || queryFields.some((field) => {
return compareStrings(item[field], filter.value.value);
});
});
break;
case DATA_TYPES.DATE:
return selectedFilters.every((filter) => {
const itemValue = item[filter.relatedField];
if (!itemValue) {
return false;
}
const boundryType = filter.value.value;
const boundryValue = filter.value.date;
if (boundryType === 'from') {
return itemValue >= boundryValue;
}
return itemValue <= boundryValue;
});
break;
}
});
return filteringResults.every((result) => result);
});
};
示例2: async
const doLoadout = async () => {
if (allowUndo && !store.isVault) {
reduxStore.dispatch(
actions.savePreviousLoadout({
storeId: store.id,
loadoutId: loadout.id,
previousLoadout: store.loadoutFromCurrentlyEquipped(
t('Loadouts.Before', { name: loadout.name })
)
})
);
}
let items: DimItem[] = copy(_.flatten(Object.values(loadout.items)));
const loadoutItemIds = items.map((i) => {
return {
id: i.id,
hash: i.hash
};
});
// Only select stuff that needs to change state
let totalItems = items.length;
items = items.filter((pseudoItem) => {
const item = getLoadoutItem(pseudoItem, store);
// provide a more accurate count of total items
if (!item) {
totalItems--;
return true;
}
const notAlreadyThere =
item.owner !== store.id ||
item.location.inPostmaster ||
// Needs to be equipped. Stuff not marked "equip" doesn't
// necessarily mean to de-equip it.
(pseudoItem.equipped && !item.equipped) ||
pseudoItem.amount > 1;
return notAlreadyThere;
});
// only try to equip subclasses that are equippable, since we allow multiple in a loadout
items = items.filter((item) => {
const ok = item.type !== 'Class' || !item.equipped || item.canBeEquippedBy(store);
if (!ok) {
totalItems--;
}
return ok;
});
// vault can't equip
if (store.isVault) {
items.forEach((i) => {
i.equipped = false;
});
}
// We'll equip these all in one go!
let itemsToEquip = items.filter((i) => i.equipped);
if (itemsToEquip.length > 1) {
// we'll use the equipItems function
itemsToEquip.forEach((i) => {
i.equipped = false;
});
}
// Stuff that's equipped on another character. We can bulk-dequip these
const itemsToDequip = items.filter((pseudoItem) => {
const item = storeService.getItemAcrossStores(pseudoItem);
return item && item.owner !== store.id && item.equipped;
});
const scope = {
failed: 0,
total: totalItems,
successfulItems: [] as DimItem[]
};
if (itemsToDequip.length > 1) {
const realItemsToDequip = _.compact(
itemsToDequip.map((i) => storeService.getItemAcrossStores(i))
);
const dequips = _.map(
_.groupBy(realItemsToDequip, (i) => i.owner),
(dequipItems, owner) => {
const equipItems = _.compact(
dequipItems.map((i) => dimItemService.getSimilarItem(i, loadoutItemIds))
);
return dimItemService.equipItems(storeService.getStore(owner)!, equipItems);
}
);
await Promise.all(dequips);
}
await applyLoadoutItems(store, items, loadoutItemIds, scope);
let equippedItems: DimItem[];
if (itemsToEquip.length > 1) {
//.........这里部分代码省略.........
示例3: countAlterationOccurences
const ret = _.mapValues(alterationsByGeneBySampleKey, (alterationsBySampleId: {[sampleId: string]: ExtendedAlteration[]}, gene: string) => {
const samplesByCancerType = _.groupBy(samplesExtendedWithClinicalData,(sample:ExtendedSample)=>{
return sample[groupByProperty];
});
return countAlterationOccurences(samplesByCancerType, alterationsBySampleId);
});
示例4: keyBy
fn: (context, args) => {
const seriesStyles: { [key: string]: SeriesStyle } =
keyBy(args.seriesStyle || [], 'label') || {};
const sortedRows = sortBy(context.rows, ['x', 'y', 'color', 'size', 'text']);
const ticks = getTickHash(context.columns, sortedRows);
const font = args.font ? getFontSpec(args.font) : {};
const data = map(groupBy(sortedRows, 'color'), (series, label) => {
const seriesStyle = {
...args.defaultStyle,
...seriesStyles[label as string],
};
const flotStyle = seriesStyle ? seriesStyleToFlot(seriesStyle) : {};
return {
...flotStyle,
label,
data: series.map(point => {
const attrs: {
size?: number;
text?: string;
} = {};
const x = get(context.columns, 'x.type') === 'string' ? ticks.x.hash[point.x] : point.x;
const y = get(context.columns, 'y.type') === 'string' ? ticks.y.hash[point.y] : point.y;
if (point.size != null) {
attrs.size = point.size;
} else if (get(seriesStyle, 'points')) {
attrs.size = seriesStyle.points;
set(flotStyle, 'bubbles.size.min', seriesStyle.points);
}
if (point.text != null) {
attrs.text = point.text;
}
return [x, y, attrs];
}),
};
});
const gridConfig = {
borderWidth: 0,
borderColor: null,
color: 'rgba(0,0,0,0)',
labelMargin: 30,
margin: {
right: 30,
top: 20,
bottom: 0,
left: 0,
},
};
const result = {
type: 'render',
as: 'plot',
value: {
font: args.font,
data: sortBy(data, 'label'),
options: {
canvas: false,
colors: getColorsFromPalette(args.palette, data.length),
legend: getLegendConfig(args.legend, data.length),
grid: gridConfig,
xaxis: getFlotAxisConfig('x', args.xaxis, {
columns: context.columns,
ticks,
font,
}),
yaxis: getFlotAxisConfig('y', args.yaxis, {
columns: context.columns,
ticks,
font,
}),
series: {
shadowSize: 0,
...seriesStyleToFlot(args.defaultStyle),
},
},
},
};
// fix the issue of plot sometimes re-rendering with an empty chart
// TODO: holy hell, why does this work?! the working theory is that some values become undefined
// and serializing the result here causes them to be dropped off, and this makes flot react differently.
// It's also possible that something else ends up mutating this object, but that seems less likely.
return JSON.parse(JSON.stringify(result));
},
示例5: groupBy
groupBy(data, ({ category }) => {
if (category === 'Activities') {
return 'activity';
}
if (category === 'Animals & Nature') {
return 'animal';
}
if (category === 'Flags') {
return 'flag';
}
if (category === 'Food & Drink') {
return 'food';
}
if (category === 'Objects') {
return 'object';
}
if (category === 'Travel & Places') {
return 'travel';
}
if (category === 'Smileys & People') {
return 'emoji';
}
if (category === 'Symbols') {
return 'symbol';
}
return 'misc';
}),
示例6: analyze
analyze(events: Event[], options?: {outputRecords: boolean, period: Date[]}) {
options = {
outputRecords: false,
...options
};
// TODO: MARKイベントは件数カウントにしたい
// TODO: 全日イベントはそのまま表示したい
const days = options.period.length;
const patterns = this.eventDetector.getPatterns();
const categories = _.groupBy(patterns, (pattern) => pattern.category);
const grouped = _.groupBy(events, (event) => event.pattern.name);
const res = _.map(grouped, (events, key) => {
const sum = _.sumBy(events, (event) => event.elapsed);
const hours = this.formatNumber(sum / 1000 / 3600);
const count = events.length;
return {key, hours, count, events};
});
_.forEach(categories, (patterns, category) => {
console.log("# " + category);
let total = 0;
patterns.forEach((pattern) => {
const result = res.find((r) => r.key === pattern.name);
if (result) {
if (pattern.total !== false) {
total += result.hours;
}
if (pattern.type === EventPatternType.MARK) {
console.log("- " + pattern.name + " " + result.count + " #");
} else {
const avg = this.formatNumber(result.hours / days);
console.log(`- ${pattern.name} ${result.hours} hours. (avg ${avg})`);
}
if (options.outputRecords) {
if (pattern.type === EventPatternType.ALL_DAY) {
for (const event of result.events) {
console.log(" " +
event.end.text
);
}
}
if (pattern.type === EventPatternType.START_GUESS || pattern.type === EventPatternType.START_DEFINITE) {
for (const event of result.events) {
console.log(" " +
event.end.text + " " +
" [ " +
" from " + (event.start ? moment(event.start.datetime).format("MM-DD HH:mm") : "--") +
" to " + moment(event.end.datetime).format("MM-DD HH:mm") + " " +
" elapsed " + Math.floor(event.elapsed / 1000 / 3600) +
" ] "
);
}
}
}
}
});
const avg = this.formatNumber(total / days);
console.log(`- TOTAL: ${this.formatNumber(total)} hours. (avg ${avg})`);
console.log("");
});
}
示例7: Error
export const parseTables = (responseChunk: string): FluxTable[] => {
const lines = responseChunk.split('\n')
const annotationLines: string = lines
.filter(line => line.startsWith('#'))
.join('\n')
.trim()
const nonAnnotationLines: string = lines
.filter(line => !line.startsWith('#'))
.join('\n')
.trim()
if (_.isEmpty(annotationLines)) {
throw new Error('Unable to extract annotation data')
}
if (_.isEmpty(nonAnnotationLines)) {
// A response may be truncated on an arbitrary line. This guards against
// the case where a response is truncated on annotation data
return []
}
const nonAnnotationData = Papa.parse(nonAnnotationLines).data
const annotationData = Papa.parse(annotationLines).data
const headerRow = nonAnnotationData[0]
const tableColIndex = headerRow.findIndex(h => h === 'table')
const resultColIndex = headerRow.findIndex(h => h === 'result')
interface TableGroup {
[tableId: string]: string[]
}
// Group rows by their table id
const tablesData = Object.values(
_.groupBy<TableGroup[]>(
nonAnnotationData.slice(1),
row => row[tableColIndex]
)
)
const groupRow = annotationData.find(row => row[0] === '#group')
const defaultsRow = annotationData.find(row => row[0] === '#default')
const dataTypeRow = annotationData.find(row => row[0] === '#datatype')
// groupRow = ['#group', 'false', 'true', 'true', 'false']
const groupKeyIndices = groupRow.reduce((acc, value, i) => {
if (value === 'true') {
return [...acc, i]
}
return acc
}, [])
const tables = tablesData.map(tableData => {
const dataRow = _.get(tableData, '0', defaultsRow)
const result: string =
_.get(dataRow, resultColIndex, '') ||
_.get(defaultsRow, resultColIndex, '')
const groupKey = groupKeyIndices.reduce((acc, i) => {
return {...acc, [headerRow[i]]: _.get(dataRow, i, '')}
}, {})
const name = Object.entries(groupKey)
.filter(([k]) => !['_start', '_stop'].includes(k))
.map(([k, v]) => `${k}=${v}`)
.join(' ')
const dataTypes = dataTypeRow.reduce(
(acc, dataType, i) => ({
...acc,
[headerRow[i]]: dataType,
}),
{}
)
return {
id: uuid.v4(),
data: [[...headerRow], ...tableData],
name,
result,
groupKey,
dataTypes,
}
})
return tables
}
示例8: splitSeriesInGraphs
export function splitSeriesInGraphs(series: Serie[], maxGraph: number, maxSeries: number) {
return flatMap(groupBy(series, serie => serie.type), type => chunk(type, maxSeries)).slice(
0,
maxGraph
);
}
示例9: Date
export const transformData = (report, settings, data): any[] => {
const AGGREGATE_KEYS = [
{ key: 'Purchase Price', decimals: 2 },
{ key: 'Tax Collected', decimals: 2 },
{ key: 'Subtotal', decimals: 2 },
{ key: 'Cash Given', decimals: 2 },
{ key: '# Items', decimals: 0 },
{ key: '# Promos', decimals: 0 },
{ key: '# Uses', decimals: 0 },
{ key: 'Quantity', decimals: 0 },
{ key: 'Reorder Quantity', decimals: 0 }
];
let baseData = _.map(data, item => {
return _.reduce(report.columns, (prev, cur: any) => {
if(!cur.checked && !cur.always) { return prev; }
const value = _.get(item, cur.key, '');
prev[cur.name] = value;
if(_.isNull(value)) {
prev[cur.name] = '';
}
if(_.includes(['Purchase Time', 'Last Sold', 'Start Date', 'End Date'], cur.name)) {
if(!value) {
prev[cur.name] = 'Never';
} else {
prev[cur.name] = dateFunctions.format(new Date(value), 'YYYY-MM-DD hh:mm A');
}
}
if(cur.name === 'Purchase Method') {
prev[cur.name] = settings.invoiceMethodDisplay(value);
}
return prev;
}, {});
});
if(report.sortBy) {
baseData = _.sortBy(baseData, item => {
const value = item[report.sortBy];
if(!_.isNaN(+value)) { return +value; }
return (value || '').toLowerCase();
});
if(report.optionValues.reverseSort) {
baseData = baseData.reverse();
}
}
if(report.modifyData) {
_.each(baseData, item => {
report.modifyData(item);
});
}
let dataGroups: any = { All: baseData };
if(report.groupBy) {
dataGroups = _.groupBy(baseData, report.groupBy);
}
if(report.groupByDate) {
const DATE_KEY = 'Purchase Time';
const dateGroupBy = report.groupByDate;
_.each(dataGroups, (group, key) => {
dataGroups[key] = [];
const groupedByDate = _.groupBy(group, purchase => dateFunctions[`startOf${report.groupByDate}`](purchase[DATE_KEY]));
_.each(groupedByDate, (dateGroup: any[]) => {
const startDateValue = dateFunctions[`startOf${dateGroupBy}`](dateGroup[0][DATE_KEY]);
const endDateValue = dateFunctions[`endOf${dateGroupBy}`](dateGroup[0][DATE_KEY]);
_.each([startDateValue, endDateValue], date => {
dateFunctions.setSeconds(date, 0);
dateFunctions.setMinutes(date, 0);
});
const startDateFormatted = dateFunctions.format(startDateValue, 'YYYY-MM-DD hh:mm A');
const endDateFormatted = dateFunctions.format(endDateValue, 'YYYY-MM-DD hh:mm A');
const baseObj = {
'Purchase Time': `${startDateFormatted} - ${endDateFormatted}`,
'Purchase Method': 'Unknown'
};
_.each(AGGREGATE_KEYS, aggKey => baseObj[aggKey.key] = 0);
const aggregateObject = _.reduce(dateGroup, (prev, cur) => {
_.each(AGGREGATE_KEYS, aggKey => prev[aggKey.key] += (+cur[aggKey.key] || 0));
return prev;
}, baseObj);
_.each(AGGREGATE_KEYS, aggKey => aggregateObject[aggKey.key] = aggregateObject[aggKey.key].toFixed(aggKey.decimals));
//.........这里部分代码省略.........
示例10: groupByPlugin
groupByPlugin() {
return _.groupBy(this, (entity) => {
return entity.pluginId;
});
}