@thoshpathi/utils-core
Version:
A collection of core utility functions for data processing
82 lines (80 loc) • 2.2 kB
JavaScript
// src/group_utils.ts
function groupByMap(array, key) {
return array.reduce((map, item) => {
const k = item[key];
if (!map.has(k)) map.set(k, []);
map.get(k).push(item);
return map;
}, /* @__PURE__ */ new Map());
}
function groupByObject(array, key) {
const result = /* @__PURE__ */ Object.create(null);
for (const item of array) {
const groupKey = String(item[key]);
if (!result[groupKey]) result[groupKey] = [];
result[groupKey].push(item);
}
return result;
}
function groupByKeyMap(array, key, value) {
return array.reduce((map, item) => {
const k = item[key];
if (!map.has(k)) map.set(k, []);
map.get(k).push(item[value]);
return map;
}, /* @__PURE__ */ new Map());
}
function groupByKeyObject(array, key, value) {
const result = /* @__PURE__ */ Object.create(null);
for (const item of array) {
const groupKey = String(item[key]);
if (!result[groupKey]) result[groupKey] = [];
result[groupKey].push(item[value]);
}
return result;
}
function groupByLatestMap(array, key) {
return array.reduce((map, item) => {
map.set(item[key], item);
return map;
}, /* @__PURE__ */ new Map());
}
function groupByLatestObject(array, key) {
const result = /* @__PURE__ */ Object.create(null);
for (const item of array) {
const groupKey = String(item[key]);
result[groupKey] = item;
}
return result;
}
function groupByTwoPropsMap(array, prop1, prop2) {
return array.reduce((map, item) => {
const key = `${item[prop1]}_${item[prop2]}`;
if (!map.has(key)) map.set(key, []);
map.get(key).push(item);
return map;
}, /* @__PURE__ */ new Map());
}
function groupByTwoPropsObject(array, prop1, prop2) {
const result = /* @__PURE__ */ Object.create(null);
for (const item of array) {
const key = `${item[prop1]}_${item[prop2]}`;
if (!result[key]) result[key] = [];
result[key].push(item);
}
return result;
}
function removeDuplicates(array) {
return Array.from(new Set(array));
}
export {
groupByMap,
groupByObject,
groupByKeyMap,
groupByKeyObject,
groupByLatestMap,
groupByLatestObject,
groupByTwoPropsMap,
groupByTwoPropsObject,
removeDuplicates
};