js reduce
- User
js reduce
- Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
js reduce
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
The reduce method in JavaScript is a powerful array function that allows you to reduce an array to a single value by executing a callback function on each element of the array. It iteratively applies the callback and accumulates the results.
array.reduce(callback(accumulator, currentValue, currentIndex, array), initialValue)
callback: A function that is executed for each element of the array, taking four parameters:
initialValue, if supplied.reduce() was called upon.initialValue (optional): A value to use as the first argument to the first call of the callback. If no initial value is supplied, the first element in the array will be used and skipped.
1. Summing an Array of Numbers
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
console.log(sum); // Output: 15
2. Flattening an Array of Arrays
const nestedArray = [[1, 2], [3, 4], [5]];
const flattenedArray = nestedArray.reduce((accumulator, currentValue) => accumulator.concat(currentValue), []);
console.log(flattenedArray); // Output: [1, 2, 3, 4, 5]
3. Counting Instances of Values in an Array
const names = ['Alice', 'Bob', 'Tina', 'Alice', 'Bob'];
const nameCount = names.reduce((accumulator, name) => {
accumulator[name] = (accumulator[name] || 0) + 1;
return accumulator;
}, {});
console.log(nameCount); // Output: { Alice: 2, Bob: 2, Tina: 1 }
4. Finding Maximum Value in an Array
const values = [10, 5, 100, 2, 20];
const max = values.reduce((accumulator, currentValue) => Math.max(accumulator, currentValue), values[0]);
console.log(max); // Output: 100
initialValue is not provided, reduce will throw a TypeError.reduce without an initialValue, be cautious about how it affects the first element of your array, especially with various data types.reduce method returns the value returned from the final invocation of the callback function.The reduce method is a fundamental tool in JavaScript for transforming arrays into a single value or data structure, offering great flexibility in how data can be processed and aggregated.