Javascript:使用reduce() 查找最小值和最大值? [英] Javascript: Using reduce() to find min and max values?

查看:50
本文介绍了Javascript:使用reduce() 查找最小值和最大值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类的代码,我应该在其中使用 reduce() 方法来查找数组中的最小值和最大值.但是,我们只需要使用一个调用来减少.返回数组的大小应为 2,但我知道 reduce() 方法总是返回大小为 1 的数组.我可以使用下面的代码获取最小值,但是我不知道如何获取同一个调用中的最大值.我假设一旦我获得了最大值,我就在 reduce() 方法完成后将其推送到数组中.

/*** 接受一个数字数组并返回一个大小为 2 的数组,* 其中第一个元素是 items 中最小的元素,* 第二个元素是 items 中最大的元素.** 必须通过使用单个调用减少来做到这一点.** 例如 minMax([4, 1, 2, 7, 6]) 返回 [1, 7]*/函数 minMax(items) {var minMaxArray = items.reduce((累加器,当前值) =>{返回(累加器

解决方案

诀窍在于提供一个空数组作为初始值参数

arr.reduce(callback, [initialValue])

<块引用>

initialValue [可选] 用作第一个参数的值回调的第一次调用.如果未提供初始值,则第一个将使用数组中的元素.

所以代码看起来像这样:

function minMax(items) {返回 items.reduce((acc, val) => {acc[0] = ( acc[0] === undefined || val < acc[0] ) ?价值:acc[0]acc[1] = ( acc[1] === undefined || val > acc[1] ) ?价值:acc[1]返回acc;}, []);}

I have this code for a class where I'm supposed to use the reduce() method to find the min and max values in an array. However, we are required to use only a single call to reduce. The return array should be of size 2, but I know that the reduce() method always returns an array of size 1. I'm able to obtain the minimum value using the code below, however I don't know how to obtain the max value in that same call. I assume that once I do obtain the max value that I just push it to the array after the reduce() method finishes.

/**
 * Takes an array of numbers and returns an array of size 2,
 * where the first element is the smallest element in items,
 * and the second element is the largest element in items.
 *
 * Must do this by using a single call to reduce.
 *
 * For example, minMax([4, 1, 2, 7, 6]) returns [1, 7]
 */
function minMax(items) {
     var minMaxArray = items.reduce(
        (accumulator, currentValue) => {
             return (accumulator < currentValue ? accumulator : currentValue);
        }
    );

     return minMaxArray;
 }

解决方案

The trick consist in provide an empty Array as initialValue Parameter

arr.reduce(callback, [initialValue])

initialValue [Optional] 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.

So the code would look like this:

function minMax(items) {
    return items.reduce((acc, val) => {
        acc[0] = ( acc[0] === undefined || val < acc[0] ) ? val : acc[0]
        acc[1] = ( acc[1] === undefined || val > acc[1] ) ? val : acc[1]
        return acc;
    }, []);
}

这篇关于Javascript:使用reduce() 查找最小值和最大值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆