Method encapsulation of summing, filtering and multi sorting of js array objects

In the process of data report and background management system development, we often encounter the operation of summing and filtering the data we get. In fact, it is not difficult to realize them, but if multiple pages need to do these operations, it is troublesome to write a little bit more. When some code repetition rate is too high, we need to consider optimization. Encapsulation into methods, when used to call, this is the right choice.

  • Summation
// The first parameter is the array object of the required sum, followed by the field of the required sum (indefinite item). If the field value of the required sum is a string, the corresponding conversion is also made
function obj_sum(arr, ...param) {
    var temp = {};
    arr.forEach(function(item, index) {
        for(var k in item) {
            if(param.indexOf(k) >= 0) {
                if((typeof item[k]) == 'string'){
                    item[k] = item[k]*1
                }
                if(temp[k]) {
                    temp[k] += item[k];
                } else {
                    temp[k] = item[k];
                }
            }
        }
    });
    return temp;
};
 // Here are the test data
var arr = [
     {
          "adslot_id": 16,
          "request": '1234567',
          "served_request": 12345,
          "impression": 1234,
          "click": '234',
          "income": 34,
          "app_income": 30
      },
      {
          "adslot_id": 17,
          "request": '2345678',
          "served_request": 23456,
          "impression": 2345,
          "click": 345,
          "income": 45,
          "app_income": 40
      },
      {
          "adslot_id": 18,
          "request": '3456789',
          "served_request": 34567,
          "impression": 4567,
          "click": '567',
          "income": 67,
          "app_income": 60
      }
  ];
  // The summation results of some corresponding fields can be obtained as follows
  console.log(obj_sum(arr,'request','served_request','click','app_income','income'));
  • filter
// The first parameter is the data to be filtered, the second parameter is the filtered value, followed by the filtered field
function obj_filter(data, v, ...k){
  let key = (v || '').trim();
  let keyLength = key.length;
  let keyMatcher = new RegExp(key, 'i');
  if(keyLength) {
    data = data.filter(res =>{
      let flag = false;
      for(var item of k) {
        flag = keyMatcher.test(res[item]);
        if(flag) break;
      }
      return flag;
    })
  }
  return data;
}
// The test method is the same as above
  • Multiple sorting (sorting by multiple fields at the same time)
// The first two parameters are the two parameters of the sort method. The third parameter is optional. It is the sorting attribute, that is, the field to be sorted and the sorting direction. If the third field is empty, it is sorted in ascending order according to the full attribute
function obj_sort(item1,item2) {
    // "use strict";
    var props = [];
    for (var _i = 2; _i < arguments.length; _i++) {
        props[_i - 2] = arguments[_i];
    }
    var cps = []; // Stores the sort property comparison results.
    // If the sort attribute is not specified, sort in ascending order of all attributes.
    var asc = true;
    if (props.length < 1) {
        for (var p in item1) {
            if (item1[p] > item2[p]) {
                cps.push(1);
                break; // Jump out of loop when greater than.
            } else if (item1[p] === item2[p]) {
                cps.push(0);
            } else {
                cps.push(-1);
                break; // Jump out of the loop when less than.
            }
        }
    }
    else {
        for (var i = 0; i < props.length; i++) {
            var prop = props[i];
            for (var o in prop) {
                asc = prop[o] === "ascending" ? 1 : -1;
                if (item1[o] > item2[o]) {
                    return asc;
                } else if (item1[o] < item2[o]) {
                    return -asc;
                }
            }
        }
        return 0;
    }
    for (var j = 0; j < cps.length; j++) {
        if (cps[j] === 1 || cps[j] === -1) {
            return cps[j];
        }
    }

    return false;
};
// test data
var arr = [
     {
          "adslot_id": 16,
          "request": '1234567',
          "served_request": 12345,
          "impression": 1234,
          "click": '234',
          "income": 50,
          "app_income": 30
      },
      {
          "adslot_id": 17,
          "request": '1234567',
          "served_request": 23456,
          "impression": 2345,
          "click": 345,
          "income": 45,
          "app_income": 40
      },
      {
          "adslot_id": 18,
          "request": '2456789',
          "served_request": 34567,
          "impression": 4567,
          "click": '567',
          "income": 50,
          "app_income": 60
      }
  ];
    let obj ={ "request": 'ascending', "income": 'ascending'};
    let obj1 ={ "request": 'ascending', "income": 'ascending', "app_income": 'descending'};
    console.log(
        arr.sort(function(a,b){
            return obj_sort(a,b,obj)
        })
    )
    console.log(
        arr.sort(function(a,b){
            return obj_sort(a,b,obj1)
        })
    )

Keywords: Attribute less

Added by Dollar on Mon, 04 May 2020 19:39:58 +0300