How to remove element from an Array in JavaScript?

04-Dec-2019

.

Admin

Hi Dev,

In this blog, I will learn you how to remove element of array in javascript. You can remove array elements in different ways using javascript.

You can remove elements from the beginning of an array using shift(), from the end of array using pop(), or from the perticuler and multiple using splice().

It is simple way to remove a specific element from an array as bellow example.

Example : Remove elements from the beginning of an array


shift() method is used to remove element from the beginning of an array in javascript.

<!DOCTYPE html>

<html>

<head>

<title>Remove from the beginning of Array </title>

</head>

<body>

<script type="text/javascript">

var myArray = ['abc','xyz','def','ghi','jkl','mno'];

console.log(myArray);

myArray.shift() //remove first element of array

console.log(myArray);

</script>

</body>

</html>

Example : Remove elements from the end of an array

pop() method is used to remove element from the end of an array in javascript.

<!DOCTYPE html>

<html>

<head>

<title>Remove from the end of Array </title>

</head>

<body>

<script type="text/javascript">

var myArray = ['abc','xyz','def','ghi','jkl','mno'];

console.log(myArray);

myArray.pop() //remove last element of array

console.log(myArray);

</script>

</body>

</html>

Example : Remove specific elements of an array

splice() method is used to remove perticuler element of an array in javascript.

<!DOCTYPE html>

<html>

<head>

<title>Remove specific elements of Array</title>

</head>

<body>

<script type="text/javascript">

var myArray = ['abc','xyz','def','ghi','jkl','mno'];

console.log(myArray);

//Index start with zero.

myArray.splice(2,1) //remove perticuler element of array

console.log(myArray);

</script>

</body>

</html>

Example : Remove all elements of an array

splice() method is used to remove all element of an array in javascript.

<!DOCTYPE html>

<html>

<head>

<title>Remove all elements of Array </title>

</head>

<body>

<script type="text/javascript">

var myArray = ['abc','xyz','def','ghi','jkl','mno'];

console.log(myArray);

//Index start with zero.

myArray.splice(0,myArray.length) //remove all element of array

console.log(myArray);

</script>

</body>

</html>

Example : Remove multiple elements of an array

filter() function is used to remove multiple element of an array in javascript.

<!DOCTYPE html>

<html>

<head>

<title>Remove multiple elements of Array </title>

</head>

<body>

<script type="text/javascript">

var ar = [1,2,3,4,5,6,7,8,9,0];

console.log(ar);

var filtered = ar.filter(function(value){

return value > 5;

});

console.log(filtered);

</script>

</body>

</html>

It will help you...

#JavaScript