javascript - Comment puis-je supprimer un objet spécifique d'un tableau

Mots clés : javascriptarraysjavascript

meilleur 5 Réponses javascript - Comment puis-je supprimer un objet spécifique d'un tableau

vote vote

98

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); 
function removeItemOnce(arr, value) {   var index = arr.indexOf(value);   if (index > -1) {     arr.splice(index, 1);   }   return arr; }  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))
function removeItem<T>(arr: Array<T>, value: T): Array<T> {    const index = arr.indexOf(value);   if (index > -1) {     arr.splice(index, 1);   }   return arr; } 
vote vote

86

var value = 3  var arr = [1, 2, 3, 4, 5, 3]  arr = arr.filter(function(item) {     return item !== value })  console.log(arr) // [ 1, 2, 4, 5 ] 
let value = 3  let arr = [1, 2, 3, 4, 5, 3]  arr = arr.filter(item => item !== value)  console.log(arr) // [ 1, 2, 4, 5 ] 
let forDeletion = [2, 3, 5]  let arr = [1, 2, 3, 4, 5, 3]  arr = arr.filter(item => !forDeletion.includes(item)) // !!! Read below about array.includes(...) support !!!  console.log(arr) // [ 1, 4 ] 
// array-lib.js  export function remove(...forDeletion) {     return this.filter(item => !forDeletion.includes(item)) }  // main.js  import { remove } from './array-lib.js'  let arr = [1, 2, 3, 4, 5, 3]  // :: This-Binding Syntax Proposal // using "remove" function as "virtual method" // without extending Array.prototype arr = arr::remove(2, 3, 5)  console.log(arr) // [ 1, 4 ] 
vote vote

72

array.splice(i, 1); 
for (var i = array.length - 1; i >= 0; i--) {  if (array[i] === number) {   array.splice(i, 1);  } } 
delete array[i]; 
vote vote

67

array[index] = undefined; 
//To keep the original: //oldArray = [...array];  //This modifies the array. array.splice(index, 1); 
var value = array.splice(index, 1)[0]; 
vote vote

58

function removeAllInstances(arr, item) {    for (var i = arr.length; i--;) {      if (arr[i] === item) arr.splice(i, 1);    } } 

Questions similaires