繁体   English   中英

在类似数组的对象中查找最小值和最大值

[英]finding min and max value in an object like array

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

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

我有一个像数组对象

它的值是

{
    0:exchange:bitfix

    totaleth:334

    1:exchange:coinbase

    totaleth:6000

    2:exchange:koinex

    totaleth:3000
}

现在这个对象就像一个数组,我想显示基于totaleth字段的最小值和最大值,请问任何一个都有解决方案

我尝试了诸如map reduce for loop之类的各种操作,似乎没有任何作用

假设有一个对象数组,则可以通过采用最小值和最大值来缩小数组。

 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); 

好的,因此您可以使用排序功能,但是请记住,它会修改原始数组。

const someArr = [{"_id":"5c585ed5a9a5b931c3057d48","exchange":"Poloniex","totaleth":-338,"dt":"2019-02-04T15:48:37.232Z","__v":0},{"_id":"5c585ed5a9a5b931c3057d47","exchange":"Bitrex","totaleth":-227,"dt":"2019-02-04T15:48:37.222Z","__v":0},{"_id":"5c585ed5a9a5b931c3057d46","exchange":"Gemini","totaleth":86,"dt":"2019-02-04T15:48:37.220Z","__v":0},{"_id":"5c585ed5a9a5b931c3057d45","exchange":"Bitfinex","totaleth":-373,"dt":"2019-02-04T15:48:37.219Z","__v":0},{"_id":"5c585ed4a9a5b931c3057d44","exchange":"Binance","totaleth":6531,"dt":"2019-02-04T15:48:36.586Z","__v":0}];

console.log(
  someArr.sort((a, b) => {
    return a.totaleth - b.totaleth;
  })
);

您的代码成功了,非常感谢nina scholz

 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); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM