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
Asked
Active
Viewed 9,024 times
0
-
2Possible duplicate of [How might I find the largest number contained in a JavaScript array?](https://stackoverflow.com/questions/1379553/how-might-i-find-the-largest-number-contained-in-a-javascript-array) – Josh Jul 16 '18 at 14:30
-
Can you sort it first? – Simeon Smith Jul 16 '18 at 14:30
-
Any attempt??????? – Mamun Jul 16 '18 at 14:31
-
Sort the array and take the `top` – Harun Or Rashid Jul 16 '18 at 14:31
-
2filter() is the wrong tool for the job – charlietfl Jul 16 '18 at 14:32
-
Sorting would work but it's less efficient than simply finding the largest value in a single pass over the array. – Pointy Jul 16 '18 at 14:33
-
@charlietfl This sounds like a puzzle question, not about how to do it the best way. – Barmar Jul 16 '18 at 14:57
3 Answers
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
-
if i am not wrong, a stands for elements of array ,b for index,c for array but what does d indicates – JustaGamer Jul 16 '18 at 15:14
-
You are exactly right. d is extra. i forgot to remove it. simple and practical ways. – Hassan Sadeghi Jul 16 '18 at 15:34