Find the min/max element of an Array in JavaScript

2018-12-31 01:11发布

How can I easily obtain the min or max element of a JavaScript Array?

Example Psuedocode:

let array = [100, 0, 50]

array.min() //=> 0
array.max() //=> 100

标签: javascript
30条回答
看淡一切
2楼-- · 2018-12-31 02:00

For big arrays (~10⁷ elements), Math.min and Math.max both produces the following error in Node.js.

RangeError: Maximum call stack size exceeded

A more robust solution is to not add every element to the call stack, but to instead pass an array:

function arrayMin(arr) {
  return arr.reduce(function (p, v) {
    return ( p < v ? p : v );
  });
}

function arrayMax(arr) {
  return arr.reduce(function (p, v) {
    return ( p > v ? p : v );
  });
}

If you are concerned about speed, the following code is ~3 times faster then Math.max.apply is on my computer. See http://jsperf.com/min-and-max-in-array/2.

function arrayMin(arr) {
  var len = arr.length, min = Infinity;
  while (len--) {
    if (arr[len] < min) {
      min = arr[len];
    }
  }
  return min;
};

function arrayMax(arr) {
  var len = arr.length, max = -Infinity;
  while (len--) {
    if (arr[len] > max) {
      max = arr[len];
    }
  }
  return max;
};

If your arrays contains strings instead of numbers, you also need to coerce them into numbers. The below code does that, but it slows the code down ~10 times on my machine. See http://jsperf.com/min-and-max-in-array/3.

function arrayMin(arr) {
  var len = arr.length, min = Infinity;
  while (len--) {
    if (Number(arr[len]) < min) {
      min = Number(arr[len]);
    }
  }
  return min;
};

function arrayMax(arr) {
  var len = arr.length, max = -Infinity;
  while (len--) {
    if (Number(arr[len]) > max) {
      max = Number(arr[len]);
    }
  }
  return max;
};
查看更多
无与为乐者.
3楼-- · 2018-12-31 02:00

Using spread operator (ES6)

Math.max(...array);  // the same with "min" => Math.min(...array);

const array = [10, 2, 33, 4, 5];

console.log(
  Math.max(...array)
)

查看更多
残风、尘缘若梦
4楼-- · 2018-12-31 02:04

Math.min & Math.max

The Math.min and Math.max are both recursive operations which most likely crach for big arrays (greater than ~10⁷ items).

Instead, you can use old javascript loops like so:

function getMinMax(arr) {
    return arr.reduce(({min, max}, v) => ({
        min: min < v ? min : v,
        max: max > v ? max : v,
    }), { min: arr[0], max: arr[0] });
}

Or (better run-time):

function getMinMax(arr) {
    let min = arr[0];
    let max = arr[0];
    let i = arr.length;

    while (i--) {
        min = arr[i] < min ? arr[i] : min;
        max = arr[i] > max ? arr[i] : max;
    }
    return { min, max };
}

* Tested with 1,000,000 items:
Just for a reference, the 1st function run-time (on my machine) was 15.84ms vs 2nd function with only 4.32ms.

查看更多
高级女魔头
5楼-- · 2018-12-31 02:05

Using Math.max() or Math.min()

Math.max(10, 20);   //  20
Math.min(-10, -20); // -20

The following function uses Function.prototype.apply() to find the maximum element in a numeric array. getMaxOfArray([1, 2, 3]) is equivalent to Math.max(1, 2, 3), but you can use getMaxOfArray() on programmatically constructed arrays of any size.

function getMaxOfArray(numArray) {
  return Math.max.apply(null, numArray);
}

Or with the new spread operator, getting the maximum of an array becomes a lot easier.

var arr = [1, 2, 3];
var max = Math.max(...arr); // 3
var min = Math.min(...arr); // 1
查看更多
孤独寂梦人
6楼-- · 2018-12-31 02:06

I like Linus's reduce() approach, especially for large arrays. But as long as you know you need both min and the max, why iterate over the array twice?

Array.prototype.minmax = function () {
  return this.reduce(function (p, v) {
    return [(p[0] < v ? p[0] : v), (p[1] > v ? p[1] : v)];
  }, [this[0], this[0]]);
}

Of course, if you prefer the iterative approach, you can do that too:

Array.prototype.minmax = function () {
    var mn = this[0], mx = this[0];
    this.forEach(function (v) {
        if (v < mn) mn = v;
        if (v > mx) mx = v;
    });
    return [mn, mx];
};
查看更多
ら面具成の殇う
7楼-- · 2018-12-31 02:07

https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Math/max

function getMaxOfArray(numArray) {
  return Math.max.apply(null, numArray);
}

var arr = [100, 0, 50];
console.log(getMaxOfArray(arr))

this worked for me.

查看更多
登录 后发表回答