首页 > 解决方案 > 在像数组这样的对象中查找最小值和最大值

问题描述

我正在尝试从数组中找到最小值和最大值

尝试了各种方法,但找不到满足我需求的解决方案

我有一个数组对象

它的值为

{
    0:exchange:bitfix

    totaleth:334

    1:exchange:coinbase

    totaleth:6000

    2:exchange:koinex

    totaleth:3000
}

现在这个对象就像一个数组,我想根据 totaleth 字段显示最小值和最大值,任何 1 都有解决方案吗

我尝试了各种方法,例如 map reduce for loop,似乎没有任何效果

标签: javascriptobject

解决方案


假设一个对象数组,您可以通过取最小值和最大值来减少数组。

var array = [{ exchange: 'bitfix', totaleth: 334 }, { exchange: 'coinbase', totaleth: 6000 }, { exchange: 'koinex', totaleth: 3000 }],
    { min, max } = array.reduce(
        (r, o, i) => i
            ? {
                min: r.min.totaleth < o.totaleth ? r.min : o,
                max: r.max.totaleth > o.totaleth ? r.max : o
            }
            : { min: o, max: o },
        undefined
    );
    
console.log('min', min);
console.log('max', max);


推荐阅读