How to find the max/min of a nested array in javascript?

前端 未结 6 1610
情歌与酒
情歌与酒 2020-12-08 01:04

I want to find the maximum of a nested array, something like this:

a = [[1,2],[20,3]]
d3.max(d3.max(a)) // 20

but my array contains a text

6条回答
  •  没有蜡笔的小新
    2020-12-08 01:32

    It's a cruel hack, but looking at the source code for d3.max, your best bet might be to define a d3.max1 that discards the first element by copying that code, but replacing i=-1 with i=0. The code at that link is excerpted here. Note that I'm not a regular d3.js user, but from what I know of the library, you're going to want make sure your version has an f.call case like this function does, so that it can respond to live updates correctly.

    d3.max = function(array, f) {
      var i = -1,
          n = array.length,
          a,
          b;
      if (arguments.length === 1) {
        while (++i < n && ((a = array[i]) == null || a != a)) a = undefined;
        while (++i < n) if ((b = array[i]) != null && b > a) a = b;
      } else {
        while (++i < n && ((a = f.call(array, array[i], i)) == null || a != a)) a = undefined;
        while (++i < n) if ((b = f.call(array, array[i], i)) != null && b > a) a = b;
      }
      return a;
    };
    

    Then it would just be d3.max(d3.max1(a)).

提交回复
热议问题