js remove element from array
// Remove single item
function removeItemOnce(arr, value) {
var index = arr.indexOf(value);
if (index > -1) {
arr.splice(index, 1);
}
return arr;
}
// Remove all items
function removeItemAll(arr, value) {
var i = 0;
while (i < arr.length) {
if (arr[i] === value) {
arr.splice(i, 1);
} else {
++i;
}
}
return arr;
}
// Usage
console.log(removeItemOnce([2, 5, 9, 1, 5, 8, 5], 5));
console.log(removeItemAll([2, 5, 9, 1, 5, 8, 5], 5));var colors = ["red","blue","car","green"];
var carIndex = colors.indexOf("car");//get "car" index
//remove car from the colors array
colors.splice(carIndex, 1); // colors = ["red","blue","green"]var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.shift();var list = ["bar", "baz", "foo", "qux"];
list.shift()//["baz", "foo", "qux"]const array = [2, 5, 9];
console.log(array);
const index = array.indexOf(5);
if (index > -1) {
array.splice(index, 1);
}
// array = [2, 9]
console.log(array); let arrDeletedItems = array.splice(start[, deleteCount[, item1[, item2[, ...]]]])
Also in JavaScript:
- js while
- how to make modules structure like lodash
- h«javascript variable declaration
- video recorder using webrtc and javascript
- javascript hasclass
- dom ready js
- express js cors
- data submit notification in javascript
- jsonplaceholder
- scale text in div react
- SyntaxError: Unexpected end of JSON input while parsing near '...version":"2.0.6","devD' cli
- javascript closure inside loop
- jquery get search parameter
- check member role discordjs 12
- pop javascript
- how to convert object to array in javascript
- convert datetime to timestamp javascript
- does string contain special charactors javascript
- restrict the user from going to signup or login page if the user is already logged in firebase auth
- property 'auth' does not exist on type 'angularfireauth' angular
- how to get all elements with same class in javascript
- dont starve together
- fs.writeFileSync in pdfDocument
- express payloadtoolarge request entity too large bodyParser raw-body hydra-express