使用lodash将对象数组排序到Top N中,将n + 1作为“其他”

时间:2015-06-03 14:46:37

标签: javascript arrays json angularjs lodash

假设我有这个数据结构,示例输入:

[ {name: "a", val:1},
  {name: "b", val:2},
  {name: "c", val:3},
  {name: "d", val:4},
  {name: "e", val:5},
  {name: "f", val:1},
  {name: "g", val:2},
  {name: "h", val:1},
]

我想输出2个数组:

第一个是来自对象的val属性,首先是顶部(最高)值,然后是剩余元素的总和。如果我们假设n = 5,那么前5个结果+“其余”。所以array [5]上的这个数组=不在前5的所有val属性的总和。示例输出:

[2,3,4,5,2,3]

第二个数组将是与前5个对应的name属性,其中array [5] =“others”或其他任意字符串。示例输出:

["b","c","d","e","g","others"]

如何使用lodash以最高效率和/或最大代码清晰度实现这一目标? lodash

编辑:示例代码:

       var n = 5;
  var input = [ 
      {name: "a", val:1},
      {name: "b", val:2},
      {name: "c", val:3},
      {name: "d", val:4},
      {name: "e", val:5},
      {name: "f", val:1},
      {name: "g", val:2},
      {name: "h", val:1},
    ];
    var sortedArray = _.sortByOrder(input, ['val'], [false]);
    var topNValues = _.pluck(_.slice(sortedArray, 0, n), 'val');
    var restValues = _.pluck(_.slice(sortedArray, n, sortedArray.length), 'val');
    var restAdded = _.reduce(restValues, function(i, j) {
    return i + j;
}, 0); 
    topNValues.splice(n, 0,restAdded);
    $scope.array1 = topNValues; 
    var names = _.pluck(_.slice(sortedArray, 0, n), 'name');
    names.splice(n,0,"others");
    $scope.array2 = names;

必须有比我的jsfiddle更清晰,更有链式的方式:http://jsfiddle.net/u1w4da6r/2/

1 个答案:

答案 0 :(得分:2)

所以它不是一个单一的链,但它似乎相当容易阅读。我没有进行任何性能测试,但易于理解应该是您的主要目标。

Codepen

system>library>db>mpdo.php