
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 Certain Number of Elements from an Array in JavaScript
We are required to write a function that takes in an array of numbers and a number, and it should remove all the occurrences of that number from the array inplace.
Let’s write the code for this function.
We will make use of recursion to remove elements here. The recursive function that removes all occurrences of an element from an array can be written like.
Example
const numbers = [1,2,0,3,0,4,0,5]; const removeElement = (arr, element) => { if(arr.indexOf(element) !== -1){ arr.splice(arr.indexOf(element), 1); return removeElement(arr, element); }; return; }; removeElement(numbers, 0); console.log(numbers);
Output
The output in the console will be −
[ 1, 2, 3, 4, 5 ]
Advertisements