Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 ]
Advertisements