4

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?

Penny Liu
  • 15,447
  • 5
  • 79
  • 98
MadCatm2
  • 951
  • 4
  • 24
  • 41
  • 4
    Your logic's fine for finding the largest and smallest numbers – you just need to move the `console.log` statements outside the loop. – Rick Hitchcock Jul 07 '16 at 22:21
  • Oh wow, how did I not see that...how embarrassing. Any suggestions for getting the second largest and the second smallest? – MadCatm2 Jul 07 '16 at 22:25
  • "Any suggestions for getting the second largest and the second smallest?" --- create a function that would maintain a sorted array of N elements. Then feed it with your `numbers` array. – zerkms Jul 07 '16 at 22:26
  • @MadCatm2 Use the same algorithm, just use a new array with the same data and remove the largest and smallest from it. Or sort the array and get index `1` and `n-2` (assuming `n-1` is the last element and `0` is the first). – Spencer Wieczorek Jul 07 '16 at 22:28
  • Oh, but that would just give me my number array sorted from smallest to largest no? I just need to return one value that is the second smallest... – MadCatm2 Jul 07 '16 at 22:30

12 Answers12

9

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);
Rick Hitchcock
  • 35,202
  • 5
  • 48
  • 79
3

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

3

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
Grant Miller
  • 27,532
  • 16
  • 147
  • 165
2
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
        );
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.

Community
  • 1
  • 1
hb22
  • 383
  • 1
  • 2
  • 14
1
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);
0
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);
maja
  • 1
  • 1
0

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.

0
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())
0

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
0

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

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

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

0

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))
Ahmad Faraz
  • 1,371
  • 1
  • 4
  • 11