Skip to content Skip to sidebar Skip to footer

Check If Any Number In Array Is Bigger Than Given Number Javascript

I have this function which finds the avarage in the array : const findAvarage = (a,b,c,d) =>{ let total = 0; let numbers = [a,b,c,d]; for(let i = 0; i < numbers.length;

Solution 1:

You can achieve this with the find() method:

const array1 = [2, 2, 6, 10];

const found = array1.find(element => element > findAvarage(2,2,6,10));

console.log(found);

If you want to get back the index of the element, use findIndex() instead

Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find

Solution 2:

I saw lot of answers, but none of them has improved the find average function, it is limited to only four digits and it doesn't return the result, and even for finding the biggest number than the average, both should be dynamic

constfindAvarage = (...nums) => nums.reduce((a, b) => a + b) / nums.length || 0;

constgetBiggestNumberThanTheAverage = (...nums) => {
  let average = findAvarage(...nums);
  return nums.find(num => num > average);
}

console.log(getBiggestNumberThanTheAverage(2, 2, 6, 10));
console.log(getBiggestNumberThanTheAverage(3, 2, 7));
console.log(getBiggestNumberThanTheAverage(7, 5, 9, 10, 18, 8, 1, 6));

Solution 3:

constfindAvarage = (a,b,c,d) =>{
  let total = 0;
  let numbers = [a,b,c,d];

for(let i = 0; i < numbers.length; i++) {
    total += numbers[i];
}
let avg = total / numbers.length;

return avg;
}


let arr = [2, 2, 6, 10];

arr=arr.filter(element => element > findAvarage(2,2,6,10));

console.log(arr); //this shows all numbers > average//now to see the highest numbervar yourAnswer = arr.sort()[arr.length-1];
console.log("Your answer is "+yourAnswer);

this is just the running version

Post a Comment for "Check If Any Number In Array Is Bigger Than Given Number Javascript"