JavaScript - Remove specific element from an array
Topics related to client-side programming language.
Post questions and answers about JavaScript, Ajax, or jQuery codes and scripts.
-
MarPlo
- Posts:186
JavaScript - Remove specific element from an array
I have an array of integers:
Is there a simple way to remove a specific element from an array? The equivalent of something like:
I have to use pure JavaScript - no frameworks.
Admin
Posts:805
Use the indexOf() to find the index of the element you want to remove, then apply splice() to remove it:
Code: Select all
var array = [2, 5, 9, 8];
var index = array.indexOf(5);
if (index > -1) {
array.splice(index, 1);
}
console.log(array); // [2, 9, 8]
- The second parameter of splice() is the number of elements to remove.
- splice() modifies the array in place and returns a new array containing the elements that have been removed.
Note: indexOf() is not supported in IE7-8.
drakebohan
Posts:1
You can use the
arrayObject.filter() method :
net-informations.com/js/progs/remove.htm
Example, remove 1 specific item:
Code: Select all
var rValue = 'three'
var arrayItems = ['one', 'two', 'three', 'four', 'five', 'six']
arrayItems = arrayItems.filter(item => item !== rValue)
console.log(arrayItems)
Output:
Code: Select all
[ 'one', 'two', 'four', 'five', 'six' ]
Example, remove multiple items:
Code: Select all
let forDeletion = ['two', 'three', 'four']
var arrayItems = ['one', 'two', 'three', 'four', 'five', 'five' , 'six']
arrayItems = arrayItems.filter(item => !forDeletion.includes(item))
console.log(arrayItems)
Output:
Similar Topics
- Hour and Minutes togheter in Javascript
JavaScript - jQuery - Ajax
First post
Dear Coursesweb I can not find out how to add the hours + minutes togheter.
<SCRIPT LANGUAGE= JavaScript >
day = new Date()
hr =...
Last post
See and use the following example:
<script>
var day = new Date();
let hr = day.getHours();
let mn = day.getMinutes();
let se =...
- Display message to every minute in Javascript
JavaScript - jQuery - Ajax
First post
Hello,
On eatch minute from the current hour I wanna have an message
I can not find out how to complete
I hope to get something like this (code...
Last post
If you only want to display a message to every minute, just use the setInterval() function. It calls a function repeatedly, over and over again, at...