Logo


How can I remove a specific item from an array using indexof in javascript?


Remove item from array javascript is an interesting topic. There are many ways to remove a specific item from an array, but we will discuss the most common methods.


1) Remove an item with indexOf and splice method of javascript (ES5)

1const array = [1, 2, 3, 4, 5];
2
3  console.log(array); //[1,2,3,4,5]
4
5  const index = array.indexOf(3);
6  if (index > -1) {
7    array.splice(index, 1); // 2nd parameter means remove one item only
8  }
9
10  console.log(array); //[1,2,4,5]

In line number five we are finding item '3' with the help of indexof javascript method. then we check that the item is present in the array. If an item exists then we are applying another method of the array in javascript called splice. In line number 7 splice method remove the item of the given index. The splice method modifies the original array.


2) Remove an item with filter method of javascript (ES6)

1let value = 3
2
3let arr = [1, 2, 3, 4, 5]
4arr = arr.filter(item => item !== value)
5
6console.log(arr) // [1, 2, 4, 5]

The filter method will execute on each item of the array and it will return those items that are not equal to the given value '3', which we will remove from the array.
The filter method returns a new array.


This method will remove a single item from an array if you have an array of unique values. This method is also best if you have an item repeated multiple times in an array and you want to remove it.




Related Articles :



About

Moiz is a software engineer from Arid University with a passion for writing tech tutorials and doing coding. I am continously produce JavaScript and other web development technology tutorials in concepts through easy-to-understand explanations written in plain English.I have expertise in next js ,react js ,javascript,html,bootstrap and node js.

Follow him on Twitter

Hassan is a software engineer from kohat university of science and technology with a passion for writing tech tutorials and doing javascript practices on daily basis.I have expertise in next js ,react js ,javascript,html,bootstrap and node js. Problem Solving and making concpets is my strong point.

Follow him on Twitter

Tags

Click to see all tutorials tagged with:

© Copyright 2023 Pak Annonymous | Back To Homepage | Privacy Policy
Share