簡體   English   中英

通過屬性查找多維對象中的最低數值

[英]finding the lowest numeric value in a multidimensional object by property

我有一個JSON對象,該對象是一個對象數組,我想查找具有給定屬性名稱的非空值的可能的最低值的對象。

_.min(arr, function(o){
    return o[prop];
});

這是我最后嘗試過的方法,但是似乎沒有任何選擇可以起作用或為我提供我想要的東西。 有沒有干凈的方法可以做到這一點?

Array.prototype.min = function() {
    var selector = function(a) {
        return a;
    };
    if(arguments.length>0) {
        selector = arguments[0]; //can also check if it's a function if you don't trust yourself or other developers using this extension
    }
    if(this.length==0) return null;
    var min = this[0];
    for(var i=0;i<this.length;i++) {
        if(selector(min)>selector(this[i])) min=this[i];
    }
    return min;
}

//usage
myArr.min(function(obj) {return obj.intProperty;});

https://lodash.com/docs#sortByOrder

https://lodash.com/docs#isFinite

https://lodash.com/docs#first

_.first(_.sortByOrder(arr, prop, 'asc', _.isFinite))

最干凈,最短的方法。

或者如果您不在乎Infinity

https://lodash.com/docs#isNaN

_.first(_.sortByOrder(arr, prop, 'asc', !_.isNaN))

這是一個純JavaScript解決方案。 不需要額外的庫。

var a = [
  {value: null},
  {value: "foo"},
  {value: Infinity},
  {value: 1},
  {value: -2},
  {value: 5},
  {value: 10},
  {value: 5}
]

// Filter away the invalid values
a = a.filter(function(o) {
  return typeof o.value === "number" && Number.isFinite(o.value);
})
// Sort them the way you want
.sort(function(o1, o2) {
  return o1.value > o2.value;
});

// The first object now contains the lowest value
console.log(a);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM