A PHP Error was encountered

Severity: 8192

Message: str_replace(): Passing null to parameter #3 ($subject) of type array|string is deprecated

Filename: libraries/Filtered_db.php

Line Number: 23

How to Remove a Specific Item from an Array in JavaScript
Q:

How to Remove a Specific Item from an Array in JavaScript

0

How to Remove a Specific Item from an Array in JavaScript

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Use the splice() Method

You can use the splice() method to remove the item from an array at specific index in JavaScript. The syntax for removing array elements can be given with splice(startIndexdeleteCount).

Here, the startIndex parameter specify the index at which to start splicing the array, it is required; the second parameter deleteCount is the number of elements to remove (if it is set to 0 no element will be removed). Let's check out an example to understand how it works:

<script>    
    var colors = ["Red", "Green", "Blue", "Yellow", "Orange"];
    var removed = colors.splice(2,1); // Removes the third element
    console.log(colors); // Prints: ["Red", "Green", "Yellow", "Orange"]
    console.log(removed); // Prints: ["Blue"] (one item array)
    console.log(removed.length); // Prints: 1
    
    var persons = ["Alice", "John", "Peter", "Clark", "Harry"];
    removed = persons.splice(2,2); // Removes the third and fourth elements
    console.log(persons); // Prints: ["Alice", "John", "Harry"]
    console.log(removed); // Prints: ["Peter", "Clark"]
    console.log(removed.length); // Prints: 2
    
    var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
    removed = fruits.splice(2); // Removes all elements starting at index 2
    console.log(fruits); // Prints: ["Apple", "Banana"]
    console.log(removed); // Prints: ["Mango", "Orange", "Papaya"]
    console.log(removed.length); // Prints: 3
</script>

It is important to note that the splice() method modifies the original array on which it is called on, and returns a new array of the deleted elements, or an empty array if no elements were deleted.

Also, if the second argument (i.e. deleteCount) is omitted, all elements from the start to the end of the array are removed, as you can see in the above example.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now