0

I am new to javascript ,can anyone tell me is it possible to find the largest number in an array, using filter() method ,exclusively filter() method

JustaGamer
  • 89
  • 1
  • 2
  • 7

3 Answers3

2

I know this doesn't use filter(), but you can do it with a simple sort() and return the last element.

var arr = [50,40,60,0,10,5];
var max = arr.sort((a,b)=> a-b)[arr.length-1]
console.log(max);
Damian Peralta
  • 1,846
  • 7
  • 11
0

Obviously filter is not the write function for that, but:

Math.max.apply(0, array);

If anyway you want to do this with filter, you can do something like this.

var arr = [...];
var a = arr[0];
var b = arr.filter(function(i){
  if (i > a) {
    a = i;
  }
  return i == a;
});
return b[b.length - 1];
Programmer
  • 1,973
  • 1
  • 12
  • 20
0

If you want use filter try this:

var A = [-25, 110, 1000, 31, 1,2]/*Your Array*/, max=-Infinity;
A.filter(function(a,b,c){if(a>max)max=a;});
console.log(max);

else, this is another simple way:

console.log([-25, 110, 1000, 31, 1,2].sort(function(a,b){return b-a})[0]);
Hassan Sadeghi
  • 1,316
  • 2
  • 8
  • 14