Skip to content

Instantly share code, notes, and snippets.

@papayankey
papayankey / count-by.ts
Created October 26, 2020 03:32
count array of objects by specified key
function countBy<T extends { [key: string]: any }, K extends keyof T>(
collection: T[],
key: K
) {
return Object.values(collection).reduce(
(accum: { [key: string]: any }, curr) => {
accum[curr[key]] =
accum[curr[key]] !== undefined ? (accum[curr[key]] += 1) : 1;
return accum;
},
@papayankey
papayankey / group-by.ts
Created October 26, 2020 03:30
group array of objects by specified key
function groupBy<T extends { [key: string]: any }, K extends keyof T>(
collection: T[],
key: K
) {
return Object.values(collection).reduce(
(accum: { [key: string]: any }, curr) => {
accum[curr[key]] =
accum[curr[key]] !== undefined ? [...accum[curr[key]], curr] : [curr];
return accum;
},
@papayankey
papayankey / object-filter.js
Created March 15, 2020 11:02
object property filter or picker with support for nested objects
let toString = Object.prototype.toString;
// strict object check
function isObject(value) {
return toString.call(value) === '[object Object]';
}
// strict array check
function isArray(value) {
return toString.call(value) === '[object Array]';