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
How can I remove a specific item from an array JavaScript?
Let’s say, we have an array of numbers and we added elements to it. You need to devise a simple way to remove a specific element from an array.
The following is what we are looking for −
array.remove(number);
We have to use core JavaScript. Frameworks are not allowed.
Example
The code for this will be −
const arr = [2, 5, 9, 1, 5, 8, 5];
const removeInstances = function(el){
const { length } = this;
for(let i = 0; i < this.length; ){
if(el !== this[i]){
i++;
continue;
}
else{
this.splice(i, 1);
};
};
// if any item is removed return true, false otherwise
if(this.length !== length){
return true;
};
return false;
};
Array.prototype.removeInstances = removeInstances;
console.log(arr.removeInstances(5));
console.log(arr);
Output
And the output in the console will be −
true [ 2, 9, 1, 8 ]
Advertisements