【问题标题】:Find object having maximum value for the `id` property in an array of objects在对象数组中查找具有 `id` 属性最大值的对象
【发布时间】:2014-05-07 21:45:32
【问题描述】:

在我的对象数组中,我想找到id 属性值最高的对象。

这是我的数组:

myArray = [
  {
    'id': '73',
    'foo': 'bar'
  },
  {
    'id': '45',
    'foo': 'bar'
  },
  // …
];

通常,我使用$.grep 在数组中查找值,如下所示:

var result = $.grep(myArray, function (e) {
    return e.id == 73;
});

但在这种情况下,我需要为要选择的对象提供特定的id 值。

【问题讨论】:

    标签: javascript jquery arrays object


    【解决方案1】:

    问题是说他想找到id最大的object,而不仅仅是id最大的……

    var myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}];
    
    var max = myArray.reduce(function(prev, current) {
        if (+current.id > +prev.id) {
            return current;
        } else {
            return prev;
        }
    });
    
    // max == {'id':'73','foo':'bar'}
    

    【讨论】:

      【解决方案2】:
      const students = [
        { id: 100, name: 'Abolfazl', family: 'Roshanzamir' },
        { id: 2, name: 'Andy', family: 'Madadian' },
        { id: 1500, name: 'Kouros', family: 'Shahmir' }
      ]
      

      如果你想找到最大Id的对象

      const item = students.reduce((prev, current) => (+prev.id > +current.id) ? prev : current)
       // it returns  { id: 1500, name: 'Kouros', family: 'Shahmir' }
      

      如果您想找到具有最小 ID 的对象

      const item = students.reduce((prev, current) => (+prev.id < +current.id) ? prev : current)
      // it returns {id: 2, name: "Andy", family: "Madadian"}
      

      如果您想找到最大 ID

      const max = Math.max.apply(null, students.map(item => item.id));
      // it returns 1500
      

      如果你想找到最小ID

      const min = Math.min.apply(null, students.map(item => item.id));
      // it returns 2 
      

      【讨论】:

        【解决方案3】:

        使用数组的map() 方法。使用 map 您可以提供一个迭代数组中每个元素的函数。在该函数中,您可以计算出具有最高 id 的对象。例如:

        myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}];
        
        var maxid = 0;
        
        myArray.map(function(obj){     
            if (obj.id > maxid) maxid = obj.id;    
        });
        

        这将为您提供数组中对象的最大 ID。

        然后就可以使用grep来获取相关对象了:

        var maxObj = $.grep(myArray, function(e){ return e.id == maxid; });
        

        或者,如果您只想要具有最大 id 的对象,您可以这样做:

        var maxid = 0;
        var maxobj;
        
        myArray.map(function(obj){     
            if (obj.id > maxid) maxobj = obj;    
        });
        
        //maxobj stores the object with the max id.
        

        【讨论】:

        • 使用forEach 而不是map。您无需创建一个填充了 undefined 的数组,然后立即丢弃。
        【解决方案4】:
        var max = 0;
        var myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}]
        var maxEle = myArray.map(function(ele){ if(ele.id>max){ max=ele} });
        

        map是一个遍历数组元素并执行特定操作的函数。

        【讨论】:

          【解决方案5】:
          let id = items.reduce((maxId, item) => Math.max(maxId, item.id), 0);
          

          let id = Math.max(...items.map(item => item.id).concat(0)); // concat(0) for empty array
          // slimmer and sleeker ;)
          let id = Math.max(...items.map(item => item.id), 0);
          

          这种方式比较实用,因为在空数组的情况下,返回0,不像

          Math.max.apply(null, [].map(item => item.id)) // -Infinity
          

          如果你想得到“自动增量”,你可以加1,不管数组是否为空

          // starts at 1 if our array is empty
          autoincrement = items.reduce((maxId, item) => Math.max(maxId, item.id), 0) + 1;
          

          UPD: 使用 map 的代码更短,但使用 reduce 更快,这是大型数组所感受到的

          let items = Array(100000).fill()
             .map((el, _, arr) => ({id: ~~(Math.random() * arr.length), name: 'Summer'}));
          const n = 100;
          
          console.time('reduce test');
          for (let i = 1; i < n; ++i) {
              let id = items.reduce((maxId, item) => Math.max(maxId, item.id), 0);
          }
          console.timeEnd('reduce test');
          
          console.time('map test');
          for (let i = 1; i < n; ++i) {
              let id = Math.max(items.map(item => item.id).concat(0));
          }
          console.timeEnd('map test');
          
          console.time('map spread test');
          for (let i = 1; i < n; ++i) {
              let id = Math.max(...items.map(item => item.id), 0);
          }
          console.timeEnd('map spread test');

          减少测试:163.373046875ms
          地图测试:1282.745849609375ms
          地图传播测试:242.4111328125ms

          如果我们创建一个更大的数组,spread map 将关闭

          let items = Array(200000).fill()
              .map((el, _, arr) => ({id: ~~(Math.random() * arr.length), name: 'Summer'}));
          

          减少测试:312.43896484375ms
          地图测试:2941.87109375ms
          未捕获的 RangeError:超出最大调用堆栈大小 在:15:32

          【讨论】:

            【解决方案6】:

            function reduceBy(reducer, acc) {
                return function(by, arr) {
                    return arr[arr.reduce(function(acc, v, i) {
                        var b = by(v);
                        return reducer(acc[0], b) ? [b, i] : acc;
                    }, acc || [by(arr[0]), 0])[1]];
                };
            }
            var maximumBy = reduceBy(function(a,b){return a<b;});
            
            
            var myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}];
            console.log(maximumBy(function(x){
                return parseInt(x.id,10)
            }, myArray)); // {'id':'73','foo':'bar'}

            【讨论】:

              【解决方案7】:

              使用reduce()的缩短版本

              myArray.reduce((max, cur)=>(max.likes>cur.likes?max:cur))
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 2022-07-08
                • 2018-07-09
                • 1970-01-01
                • 1970-01-01
                • 2018-12-26
                • 1970-01-01
                • 2014-11-22
                • 2013-05-06
                相关资源
                最近更新 更多