There are multiple ways to remove a specific item from an array in JavaScript, some of the most common methods are:
Using the splice()
method: The splice()
method can be used to remove an element from an array at a specific index.
let arr = [1, 2, 3, 4, 5];
let index = arr.indexOf(3); // returns 2
arr.splice(index, 1);
console.log(arr); // [1, 2, 4, 5]
Using the filter()
method: The filter()
method creates a new array with all elements that pass the test implemented by the provided function.
let arr = [1, 2, 3, 4, 5];
let filteredArr = arr.filter(item => item !== 3);
console.log(filteredArr); // [1, 2, 4, 5]
Using the slice()
method: The slice()
method can be used to return a shallow copy of a portion of an array into a new array object.
let arr = [1, 2, 3, 4, 5];
let index = arr.indexOf(3); // returns 2
let newArr = [...arr.slice(0, index), ...arr.slice(index + 1)];
console.log(newArr); // [1, 2, 4, 5]
Using the spread
operator: The spread operator ‘…’ can also be used to remove a specific item from an array.
let arr = [1, 2, 3, 4, 5];
let newArr = [...arr.filter(item => item !== 3)];
console.log(newArr); // [1, 2, 4, 5]
Note that the above examples are used to remove one specific item from the array. If you want to remove multiple items, you can use the same methods with a loop to remove the specific items one by one.
Also Read:
- How To Get The Last Character Of A String In JavaScript
- Remove The Last Character Of A String In JavaScript
- How To Validate An Email Address In JavaScript
- How To Check If An Input Field Is Empty In JavaScript
- Check If An Input Field Is A Number In JavaScript
- Confirm Password Validation In JavaScript
- How To Print A PDF File Using JavaScript
- Calculate The Number Of Days Between Two Dates In JavaScript
- How To Compare Two Dates In JavaScript
- Calculate Age With Birth Date YYYYMMDD In JavaScript
- How To Append or Add Text To A DIV Using JavaScript
- How To Get The Text Of HTML Element In JavaScript
- How To Change The Text Inside A DIV Element In JavaScript
- Show/Hide Multiple DIVs In JavaScript
- Show A DIV After X Seconds In JavaScript
- Display A JavaScript Variable In An HTML Page
- How To Generate A Random Number In JavaScript
- Bubble Sort In JavaScript
- Insertion Sort In JavaScript
- Selection Sort In JavaScript
- How To Remove A Specific Item From An Array In JavaScript
- Merge Sort In JavaScript
- Round To 2 Decimal Places In JavaScript
- SetInterval() and setTimeout() Methods In JavaScript
- Generate A Unique ID In JavaScript
- Caesar Cipher In JavaScript
- How To Reverse A String In JavaScript
- How To Loop Through A Plain JavaScript Object
- How To Open A URL In A New Tab Using JavaScript?