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 an array method that executes a reducer function on each element of the array, resulting in a single output value. It is a powerful method for performing calculations, transformations, or aggregations on arrays.
array.reduce((accumulator, currentValue, currentIndex, array) => {
// return updated accumulator
}, initialValue);
callback: A function that is called for each element in the array. It receives the following arguments:
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 the callback will start with the second element.
Sum of an Array:
const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((accumulator, currentValue) => {
return accumulator + currentValue;
}, 0);
console.log(sum); // Output: 10
Flattening an Array:
const nestedArray = [[1, 2], [3, 4], [5]];
const flattened = nestedArray.reduce((accumulator, currentValue) => {
return accumulator.concat(currentValue);
}, []);
console.log(flattened); // Output: [1, 2, 3, 4, 5]
Counting Instances of Values in an Object:
const names = ['Alice', 'Bob', 'Alice', 'Bob', 'Charlie'];
const count = names.reduce((accumulator, currentValue) => {
accumulator[currentValue] = (accumulator[currentValue] || 0) + 1;
return accumulator;
}, {});
console.log(count); // Output: { Alice: 2, Bob: 2, Charlie: 1 }
Finding the Maximum Value:
const values = [1, 3, 5, 2, 6, 0];
const max = values.reduce((accumulator, currentValue) => {
return Math.max(accumulator, currentValue);
});
console.log(max); // Output: 6
reduce method does not mutate the original array.reduce will throw a TypeError.Using reduce can lead to more concise and expressive code, especially for complex transformations or aggregations of data.