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
- [Simple Way]-Cascading DropDownList in Asp.Net Mvc Using Jquery Ajax
- jQuery Ajax GET Example with Parameters
- How to Pass Parameters in AJAX POST?| JQuery Ajax Post Json Example
- [Simple Way]-How to get data from database using JQuery Ajax in asp net MVC
- How to add, edit and delete rows of an HTML table with Jquery?
- Registration form with image upload in MVC using jquery Ajax
- How to make an Inline editable table in MVC using jquery?
- Insert Update Delete Using Jquery Ajax and Modal Popup in Mvc
- [Solved]-How to Upload pdf file using jquery MVC?
- Dynamically creating graphs with jQuery
- Loop and interval hybrid in javascript?
- typeahead twitter not working
- can't reset form input using ng-click
- Semantic ui tab update
- HTML - Create a left menu occupying a part of the main page
- Can't send value to my controller home.php using Ajax
- How to consume non rest wcf service using Jquery?
- image swap click jquery, 3 images
- Isotope.js - WhiteSpace between element
- ChartJS - Display a single line data in tooltip
- Padding On Tablet Device
- I'm trying to use jQuery to disable form inputs. It sometimes works and sometimes doesn't
- How to trigger click event in backboon.js view in css3 style without div id or class name
- load scene in json using sceneLoader
- center cells when Adding row to datatable
- Better way to access siblings
- How to get rid from ?callback=myCallback&_=1340513330866?
- fixed sticky header expanding
- Better solution for dealing with large number of click events with Jquery
- I have multiple tabs on my page and I want the first tab open be default every time users come to that page
- Appending a div for responsive sites
- D3 oncontext menu , change node color selected
- form POST not working with huge json string; is there any other way to load a page with a huge amount of POST data?
- When does UIWebView start recognising Javascript code
- Jeditable sends no variables
- jQuery animate opacity with div.fadehover not working at all in IE8
- identify link id's clicked and pass it to javascript function
- Download file from different origin using POST request
- closing a window popup based on result
- JQuery - Icons instead of Messages Validations
- Extracting values from Rails collection using JavaScript
- Appending html elements to a table
- MVC Html.TextBox (not For) client side validation styling
- Grabbing twitter feed in bootstrap slideshow
- Swipe support with bootstrap carousel
- how to stop a nested function in javascript?
- How to submit same name elements in mvc4
- Form validation HTML & JAVASCRIPT
- How do I toggle video mute in an iframe?
- Javascript export div to image
- How do I add a "Order for Pickup" button to my popup window allowing to proceed to checkout?
- Convert a Json response to Obj in JQuery (Symfony2)
- how to take a value from one div to another onclick
- WCF Returns Result but Javascript gives Error
- How to make auto click?
- Perform an struts action and prevent the user from reprocessing until done
- acces cookie at children directorie
- Check if option is selected appear an other option value
- make all links on page have an image or affect added to them
- arduino esp8266webserver error in returning json
- How to not validate certain inputs
- How to update an input ngModel by updating its value?
- Function in not define on resize
- How to set <img> alt tag from another piece of HTML in the same page
- object literals inside constructor
- Parse retrieve a particular user information and display it (Javascript)
- Binding a generic list with knockout.js in MVC5
- Why isn't working this bounce effect in jquery?
- jQuery function works in chrome but not other browser
- Using prependTo for one element of a class loads all elements with same class
- Getting the opened BS Panel to the top of the page
- Jquery match for json data
- How to clear bootstrap progress bar
- Block specific images so they won't load
- jQuery validate remote message
- Detect IE 7 Emulate while running in IE 8+
- Jquery bind scroll listener dynamiclly
- Issue on jQuery to Customize a Phone Filed Input Box
- retrieve mysql data using jquery and php
- How to insert datatable content from JSON response object
- Printing jsonp with console or alert
- Remember and pass value by clicking back button
- mapping all possible string value from nested object into an array asumming key and structure is unknown
- jQuery - Append and Remove HTML code
- Jqplot graph is not displaying inside nested div tags
- jQuery ajax returns [object Error]
- jQuery outerHeight() returns 0 even with jQuery(window).load()
- Chrome app - load external content into div
- Passing Query string values through ajax html(data)
- resize jqgrid when splitter of jquery layout is dragged
- Highlight (Select) text in textarea when button pressed
- Get all xml files from a certain folder with AJAX
- Increment javascript variable function onclick
- Making a div with position fixed or absolute auto hides overflow content in IE8
- Embedded Bootstrap Datepicker Will Not Persist
- Ajax loader image before actual image loads
- Two rows of divs floating right
- Flexslider carousel / slider not showing - possible conflict?
- JQuery Unused Variable Error
- jQuery slideshow showing an empty slide on the end
- Combining two $.each functions
- Jquery is not loading in <ion-nav-view> templates in ionic
- Position info box next to autosized gallery
- Check All the checkboxes in a table when a particular checkbox is clicked?
- Jquery pairing of items
- Footer top position is smaller on home page, but normal size on others
- How to make scroll-based animations using JQuery work with Bootstrap 3 modals?
- jquery datatables server side process with external form
- Correct way to use multiple AJAX actions?
- use fullcalendar as generic week event management
- jQuery "focus" works in one instance but not in others
- Navigating to multiple pages using jquery mobile
- jQuery / Js — Accessing Variables in a Function
- How to display a single image using JS/JQ from a query?
- Convert date string to readable way using JS
- instagram descriptions throws js error
- JQuery click event triggered on Chrome and FF device touch emulation?
- ASP.NET Web Api fails on getJSON async
- Jquery function creates an anomolous pause
- Fancybox in the size of the div
- How to access divs of mutiple html pages in single .js file
- jQuery fireing all modal windows at once, even with different target #id
- Bootstrap not being applied to a dynamically loaded table in datatables
- How can I send value inside select event?
- Passing variable from ajax to php fails
- Sum 50% more in the value of the property when click
- Menu navigation not working with jquery datepicker
- jQuery replace div with clone
- load menu from one site into another with header data
- Creating a full window checker to select color
- Get other ID's value in form using .innerHTML
- Whenever I try and load my JSON data into my listview or select menu, nothing shows up
- Open select box on Focus
- use a request dispatcher with Jquery/AJAX
- Get GridRow value when click edit button using javascript
- How to add a class to the last elements of a row
- AutoSuggest Using jquery.tokeninput.js in Repeater Contol in asp.net c#
- Passing a 2d array from controller to model in codeigniter
- Pass Model to javascript change event from Kendo DropdownList
- Boostrap-Select Get Latest Chosen Option on Change Event
- Working with for but not with $.each
- wrong JSON data passes from PHP to AJAX
- Request JSON data in WCF REST Service and call through jQuery
- Make a div position relative to another that is static
- How to set location of iframe created by external javascript?
- How to implement jQuery's load() function in Javascript?
- JQuery replacewith not working after Ajax call
- Multiple Ckeditor using javascript Class
- How do I create a responsive navigation bar?
- jQuery animate, hide to a certain position
- SSL Error while sending an ajax call with FormData object
- How can I use Javascript to handle form data & display a separate results page?
- Blueimp file upload "Not found" only on AWS ec2 instance
- Using JQuery with Master Page
- Validating content pages using Jquery
- jQuery "find()" causing a win32 error in Internet Explorer 10, but not 9
- jquery create simple image slideshow animation - fade in and out image
- Use model attribute value in differnt views
- Need help on slider with JQuery
- How to change check state of parented checkbox group