常用js功能封装


计算相同数组个数
function totalArr(arry) {

  var arr = []  
  var result = arry
  result.sort()
  for (var i = 0; i < result.length;) {
    var count = 0;
    for (var j = i; j < result.length; j++) {
      if (result[i] === result[j]) {
        count++;
      }
    }
    var newArr = []
    newArr.push(result[i], count)
    arr.push(newArr)
    i+=count;
  }
  return arr;
  
}
var resultArr = ['北京', '北京', '北京', '上海', '广州', '广州']
var ss = totalArr(resultArr)


多维数组根据对象进行排序
var arr = [
    {name:'zopp',age:0},
    {name:'gpp',age:18},
    {name:'yjj',age:8}
];

function compare(property){
    return function(a,b){
        var value1 = a[property];
        var value2 = b[property];
        return value1 - value2;
    }
}
console.log(arr.sort(compare('age')))

你可能感兴趣的:(常用js功能封装)