Aplicaciones del método reduce en Arrays (JS)

// media
average(nums) {
return nums.reduce((a, b) => a + b) / nums.length;
}

// remove duplicated items
let data = [1, 2, 3, 1, 4, 3, 3, 5, 5, 5, 8, 9]
let myOrderedArray = data.reduce(function (accumulator, currentValue) {
if (accumulator.indexOf(currentValue) === -1) {
accumulator.push(currentValue)
}
return accumulator
}, []);

// Finding repeated items in an array
const pounds = [11, 21, 16, 19, 46, 29, 46, 19, 21];

const count = pounds.reduce( (data, pound) => {
data[pound] = (data[pound] || 0) + 1 ;
return data;
} , {})

// Grouping objects by a property
let student = [
{ name: 'Rick', enrollment: 60 },
{ name: 'Beth', enrollment: 40 },
{ name: 'Jerry', enrollment: 40 }
];

function groupBy(objectArray, property) {
return objectArray.reduce(function (accumulator, obj) {
let key = obj[property]
if (!accumulator[key]) {
accumulator[key] = []
}
accumulator[key].push(obj)
return accumulator
}, {})
}

let groupedStudent = groupBy(student, 'enrollment')
console.log(groupedStudent)

Scroll al inicio