In this article, we will learn, How can I remove a specific item from an array in javascript.I have specially written this article for less experienced developers and anyone looking for same.

I came across a situation where I have to remove multiple items from an array object. There are multiple ways to remove a specific item from an array. Now we will see some of the easiest techniques to do this task.

As you can see in above code ,I have created an array and I’m using the .push() method to push elements to the array.Now I want to delete or remove a specific element from an array.
For that i have create a global generic .DeleteItem() function so that you can use it like .push() method
Something like this:
.DeleteItem(“John”)

This function removes all of the items from the array that match with arguments.

Using using indexOf and splice

<!DOCTYPE html>
<html>
<head>
    <title>Deleting array elements in JavaScript</title>
</head>
<body>
    <script type="text/javascript">
        const employeearray = ["John", "Smith", "Ally", "Mark", "Smith"];
        function DeleteItem(array) {
            var what, a = arguments, L = a.length, ax;
            while (L > 1 && array.length) {
                what = a[--L];
                while ((ax = array.indexOf(what)) !== -1) {
                    array.splice(ax, 1);
                }
            }
            return array;
        }
        DeleteItem(employeearray,"Smith");
        console.log(employeearray);
    </script>
</body>
</html>

Using Filter

<script type="text/javascript">
        //With A one-liner code using filter,
        // Remove item 'seven' from array
        var filteredAry1 = employeearray.filter(function (e) { return e !== 'Smith' })
          //or
        var filteredAry2 = employeearray.filter(e => e !== 'Smith')
        console.log(filteredAry1)
        console.log(filteredAry2)
</script>

Using Move on Trick

<script type="text/javascript">
        //Find and move (move):        
         function removebymove(arr, val) {
            var j = 0;
            for (var i = 0, l = arr.length; i < l; i++) {
                if (arr[i] !== val) {
                    arr[j++] = arr[i];
                }
            }
            arr.length = j;
        }
        removebymove(employeearray, 'Smith')
        console.log(employeearray);
</script>

it works better if you only want to remove or delete one occurrence of an element.
There are many excellent ways to achieve this task, you can choose one of them for your solution.

The post [Solved]-How can I remove a specific item from an array in JavaScript? appeared first on Software Development | Programming Tutorials.



Read More Articles