Answers for "remove. item from array javascript"

19

how to remove element from array in javascript

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"]
Posted by: Guest on April-23-2020
49

remove element from array javascript

// 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));
Posted by: Guest on February-18-2021

Code answers related to "remove. item from array javascript"

Code answers related to "Javascript"

Browse Popular Code Answers by Language