I am trying to find the maximum one-digit integer in an array.
Let's say I have an array:
[-6, -91, 1011, -100, 84, -22, 0, 1, 743]
The maximum integer is 1011
which I have found using:
Math.max.apply(0,array)
But I need to find a maximum one-digit integer. Is there any method to find it. The output should be 1
as per the above array.
I am trying to find the maximum one-digit integer in an array.
Let's say I have an array:
[-6, -91, 1011, -100, 84, -22, 0, 1, 743]
The maximum integer is 1011
which I have found using:
Math.max.apply(0,array)
But I need to find a maximum one-digit integer. Is there any method to find it. The output should be 1
as per the above array.
- what do You expect if nothing is found? – fedeghe Commented Sep 5, 2020 at 14:28
- it would be nice to have an answer – fedeghe Commented Sep 5, 2020 at 15:56
6 Answers
Reset to default 4Math.max(...myArray.filter((n) => Math.abs(n) < 10))
You can use filter
to get single digits and Math.max to find maximum of single digist
let Arr = [-6, -91, 1011, -100, 84, -22, 0, 1, 743];
let singleDigits = Arr.filter(e => e >= -9 && e <= 9);
if(singleDigits.length){
console.log(Math.max(...singleDigits));
}else{
console.log('there is no single digit number.')
}
I would just use reduce
let Arr = [-6, -91, 1011, -100, 84, -22, 0, 1, 743];
const maxOneigit = Arr.reduce((acc, el) => {
return (el > -10 && el < 10 && el > acc) ? el : acc
}, null)
moreover this falsy null
allows You to clearly define what You expect from that function when no integers in the {-9, 9} interval are found
B_POS = []
C_NEG = []
C_NEG_Up = []
B_POS_Up = []
def solution(A):
A.sort()
print(A)
for j in A:
if j < 0:
C_NEG.append(j)
if (len(str(j)) == 2):
C_NEG_Up.append(j)
else:
B_POS.append(j)
if (len(str(j)) == 1):
B_POS_Up.append(j)
both = B_POS_Up + B_POS_Up
print(max(both,default = None))
A = [ -91, 1011, -100,184,0,-22, 473] solution(A)
Here is the simple C solution.
#include <stdio.h>
int find_max_single_digit(int arr[], int size) {
int result = 0;
for(int i = 0; i<size; i++) {
/*
* -9 to 9 will be single digit
*/
if (arr[i] > -10 && arr[i] < 10) {
if(arr[i] > result) {
result = arr[i];
}
}
}
return result;
}
int main()
{
int arr[]= {-6, -91, 1011, -100, 84, -22, 0, 1, 743};
int result = 0;
int size = sizeof(arr)/sizeof(arr[0]);
result = find_max_single_digit(arr, size);
printf("result = %d\n",result);
return 0;
}
This can be achieved in php using the below
$num = [];
array_filter($data_array, function($n) use (&$num) {
if($n >= 1 && $n < 10) {
array_push($num, $n);
}
});
return (max($num));