Skip to content

Instantly share code, notes, and snippets.

function chunk(list, size) {
return list.reduce(
(acc, item) => {
let lastIndex = acc.length - 1;
if (acc[lastIndex].length >= size) {
acc.push([]);
lastIndex++;
}
acc[lastIndex].push(item);
return acc;
{
Gryffindor: [
{ name: "Harry Potter", house: "Gryffindor", points: 40 },
{ name: "Hermione Granger", house: "Gryffindor", points: 140 }
],
Slytherin: [
{ name: "Draco Malfoy", house: "Slytherin", points: -20 },
{ name: "Lin Manuel Miranda", house: "Slytherin", points: 5000 },
{ name: "Taylor Swift", house: "Slytherin", points: 100 }
],
function groupBy(list, iteratee) {
return list.reduce((acc, item) => {
const index = iteratee(item);
if (!acc[index]) {
acc[index] = [];
}
acc[index].push(item);
return acc;
}, {});
}
{
"Harry Potter": {name: "Harry Potter", house: "Gryffindor", points: 40},
"Hermione Granger": {name: "Hermione Granger", house: "Gryffindor", points: 140},
"Draco Malfoy": {name: "Draco Malfoy", house: "Slytherin", points: -20},
"Lin Manuel Miranda": {name: "Lin Manuel Miranda", house: "Slytherin", points: 5000},
"Taylor Swift": {name: "Taylor Swift", house: "Slytherin", points: 100},
"Cedric Diggory": {name: "Cedric Diggory", house: "Hufflepuff", points: 12},
"Sally Perks": {name: "Sally Perks", house: "Hufflepuff", points: 15},
"Luna Lovegood": {name: "Luna Lovegood", house: "Ravenclaw", points: 100},
"Cho Chang": {name: "Cho Chang", house: "Ravenclaw", points: 10 }
function keyBy(list, key) {
return list.reduce((acc, item) => {
const index = item[key];
acc[index] = item;
return acc;
}, {});
}
const HarryPotter = {
name: "Harry Potter",
house: "Gryffindor",
points: 40
};
const HermioneGranger = {
name: "Hermione Granger",
house: "Gryffindor",
points: 140
};
function reduce(list, callback, initialValue) {
let accumulator = initialValue;
for (let currentIndex = 0; currentIndex < list.length; currentIndex++) {
currentValue = list[currentIndex];
accumulator = callback(accumulator, currentValue, currentIndex, list);
}
return accumulator;
}
function reduce(list, callback, initialValue) {
if (list == null || !Array.isArray(list)) {
throw new TypeError("list is not a valid array");
}
if (typeof callback !== "function") {
throw new TypeError(callback + " is not a function");
}
if (initialValue === undefined && list.length === 0) {
throw new TypeError("Reduce of empty array with no initial value");
}
list.reduce(callback, initialValue)
const callback = (accumulator, currentValue, currentIndex, list) => accumulator;