Remove smallest number in Array JavaScript


We are required to write a JavaScript function that takes in an array of numbers. The number should find the smallest element in the array and remove it in place.

The code for this will be −

const arr = [2, 1, 3, 2, 4, 5, 1];
const removeSmallest = arr => {
   const smallestCreds = arr.reduce((acc, val, index) => {
      let { num, ind } = acc;
      if(val >= num){
         return acc;
      };
      ind = index;
      num = val;
      return { ind, num };
   }, {
      num: Infinity,
      ind: -1
   });
   const { ind } = smallestCreds;
   if(ind === -1){
      return;
   };
   arr.splice(ind, 1);
};
removeSmallest(arr);
console.log(arr);

Following is the output on console −

[ 2, 3, 2, 4, 5, 1 ]

Updated on: 09-Oct-2020

564 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements