Find smallest and largest number in array javascript

I am trying to write an algorithm that finds and smallest and largest value in an array, and the second largest and second smallest.

I tried with the following:

numbers = [2, 4, 9, 2, 0, 16, 24]

var largest = numbers[0];
var smallest = numbers[0];

for (var i = 1; i < numbers.length; i++) {

  if (numbers[i] > largest) {
    largest = numbers[i];
  } else if (numbers[i] < smallest) {
    smallest = numbers[i];
  }

  console.log(largest);
  console.log(smallest);
}

This does not seem to work and just prints out the array...what am I doing wrong?

Find smallest and largest number in array javascript

Penny Liu

12.9k5 gold badges70 silver badges86 bronze badges

asked Jul 7, 2016 at 22:19

5

The easiest way to do this would be to sort the array, then return the first two and last two elements.

Using slice() prevents the array itself from being sorted:

var numbers = [2, 4, 9, 2, 0, 16, 24];

var sorted = numbers.slice().sort(function(a, b) {
  return a - b;
});

var smallest = sorted[0],                      
    secondSmallest = sorted[1],                
    secondLargest = sorted[sorted.length - 2], 
    largest  = sorted[sorted.length - 1];

console.log('Smallest: ' + smallest);
console.log('Second Smallest: ' + secondSmallest);
console.log('Second Largest: ' + secondLargest);
console.log('Largest: ' + largest);

answered Jul 7, 2016 at 22:29

Rick HitchcockRick Hitchcock

34.4k5 gold badges46 silver badges76 bronze badges

Move your console.log statements outside of your for loop.

answered Jul 7, 2016 at 22:22

You can use the spread operator to pass each array element as an argument to Math.min() or Math.max().

Using this method, you can find the smallest and largest number in an array:

const numbers = [2, 4, 9, 2, 0, 16, 24];

const smallest_number = Math.min(...numbers);
const largest_number = Math.max(...numbers);

console.log('Smallest Value:', smallest_number); // Smallest Value: 0
console.log('Largest Value:', largest_number);   // Largest Value: 24

answered Nov 18, 2018 at 1:09

Find smallest and largest number in array javascript

Grant MillerGrant Miller

25.4k16 gold badges137 silver badges153 bronze badges

const numbers = [2, 4, 9, 2, 0, 16, 24];

//we can use reduce to find the largest and smallest number

const largest = numbers.reduce((previousValue, currentValue) =>
            previousValue > currentValue ? previousValue : currentValue
        );

const smallest = numbers.reduce((previousValue, currentValue) =>
            previousValue < currentValue ? previousValue : currentValue
        );

answered Jul 22, 2020 at 4:23

1

As Roatin Marth (edited by Mr. Llama) said in this post: https://stackoverflow.com/a/6102340/6074388 ,

You can make the arrays use math.min and math.max like below

Array.prototype.max = function() {
  return Math.max.apply(null, this);
};

Array.prototype.min = function() {
  return Math.min.apply(null, this);
};

If this causes any problems you can also use

var min = Math.min.apply(null, largest),
max = Math.max.apply(null, largest);

var min = Math.min.apply(null, numbers),
max = Math.max.apply(null, numbers);

It won't help with finding the second smallest and second largest numbers, but I find this to be a simpler solution for finding the largest and smallest numbers.

answered Jul 7, 2016 at 22:32

hb22hb22

3831 gold badge2 silver badges14 bronze badges

numbers = [2, 4, 9, 2, 0, 16, 24]
var largest = numbers[0];
var smallest = numbers[0];
for (var i = 0; i < numbers.length; i++){
    var temp = numbers[i];
    if (temp > largest)
    {
        largest = numbers[i];
    }
    if (temp < smallest)
    {
        smallest = numbers[i];
    }
}
console.log(largest);
console.log(smallest);

answered Feb 18, 2019 at 8:04

Find smallest and largest number in array javascript

var numbers = [2, 4, 9, 2, 0, 16, 24];
var largest = -Infinity;
var smallest = Infinity;

for (var i = 0; i < numbers.length; i++) {
    if (numbers[i] > largest) {
        largest = numbers[i];
    }
}

for (var i = 0; i < numbers.length; i++) {
    if (numbers[i] < smallest) {
        smallest = numbers[i];
    }
}

console.log(largest);
console.log(smallest);

answered Jul 10, 2019 at 23:43

1

You can use the reduce function for this!

var numbers = [45, 4, 9, 16, 25, 100, 43];

var max = numbers.reduce((total, value, index, array) => {
    if(index === 0) return array[0];
    return total > value ? total : value;
});
console.log(max);

var min = numbers.reduce((total, value, index, array) => {
    if(index === 0) return array[0];
    return total < value ? total : value;
});
console.log(min);

You can learn how the reduce function works here. It is really useful when you have to derive a result from all the values of an array.

I'm also using the ternary operator for less code.

answered Jul 22, 2020 at 8:08

Find smallest and largest number in array javascript

let arr = [1,2,3,4,5]


const bigandsmallNum = function(){
    const smallNum = Math.min(...arr)
    const largeNum = Math.max(...arr)
    console.log(smallNum,largeNum)

 }
console.log(bigandsmallNum())

answered May 28, 2021 at 4:39

Find smallest and largest number in array javascript

You can use reduce to return an object with largest and smallest:

const array = [22, 3, 56 , 7, 14, 100, 2, 44]

const findLargestAndSmallest = (arr) => arr.reduce((acc, cur) => {
  acc = acc.largest > cur ? 
   {...acc, largest: acc.largest} : 
   {...acc, largest: cur}
  acc = acc.smallest < cur ? 
   {...acc, smallest: acc.smallest} :
   {...acc, smallest: cur}
  return acc
}, {})

console.log(findLargestAndSmallest(array)) // { largest: 100, smallest: 2 }

// or destruct it: 

const {largest, smallest} = findLargestAndSmallest(array)
console.log(largest) // 100
console.log(smallest) // 2

answered Dec 2, 2021 at 20:40

const x = [1,2,3,4];

const y = Math.min(...x);

const z =Math.max(...x)

answered Apr 12 at 0:38

Find smallest and largest number in array javascript

How you can get the first and second largest number in array I hope this would be helpful for everyone thanks

// first method

const getLargestNumber = (nums) => {
    let largest = [0];
    for (let i = 0; i <= nums.length; i++) {
      if (largest <= nums[i]) {
        largest = nums[i]
      }
    }
    return largest;
}

const array = [0, 2, 3, 6, 6, 5]

console.log("first method", getLargestNumber(array))

// second method

const maxNumber = Math.max(...array);

console.log("Second Method", maxNumber)

// third method

const getMaxNumber = array.sort((a, b) => b - a)[0]

console.log("Third Method", getMaxNumber)

const getSecondLargest = (nums) => {
    let largest = Math.max(...nums), newArr = [];
    for (let i = 0; i <= nums.length; i++) {
      if ((nums[i] !== undefined) && !(largest <= nums[i])) {
        newArr.push(nums[i]);
      }
    }
    return Math.max(...newArr);
}

const array = [0, 2, 3, 6, 6, 5]

console.log(getSecondLargest(array))

answered Jul 22 at 19:26

Ahmad FarazAhmad Faraz

8303 silver badges9 bronze badges

numbers = [2, 4, 9, 2, 0, 16, 24]

var largest = numbers[0];
var smallest = numbers[0];

for (var i = 1; i < numbers.length; i++) {

  if (numbers[i] > largest) {
    largest = numbers[i];
  } else if (numbers[i] < smallest) {
    smallest = numbers[i];
  } 
}
  console.log(largest);
  console.log(smallest);

answered Mar 25 at 4:59

Find smallest and largest number in array javascript

1

How do you find the smallest and largest number in an array?

Algorithm to find the smallest and largest numbers in an array.
Input the array elements..
Initialize small = large = arr[0].
Repeat from i = 2 to n..
if(arr[i] > large).
large = arr[i].
if(arr[i] < small).
small = arr[i].
Print small and large..

How do I find the largest and smallest number in JavaScript?

“find largest and smallest number in an array in javascript” Code Answer's.
const arr = [14, 58, 20, 77, 66, 82, 42, 67, 42, 4].
const min = Math. min(... arr).
console. log(min).

How can you find the largest or smallest number in an array of integers in JavaScript?

You can use the spread operator to pass each array element as an argument to Math. min() or Math. max() .

How do you find the smallest and largest number in an array in C?

We can use min_element() and max_element() to find the minimum and maximum elements of the array in C++.