簡體   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