Removing

Lets image that we have an array

const myArray = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'];  

and we want to remove "Wed" from this array.


Using the spread operator

There are no mutations with this code.

function removeItem(items, itemToRemove) { 
   const index = items.indexOf(itemToRemove);
   return [. . . items.slice(0, index), . . .index.slice(index + 1)];
}

Using the concat method

The concat method joins two arrays and puts them into a single flat array.

function removeItem(items, itemToRemove) { 
   const index = items.indexOf(itemToRemove);
   return items.slice(0, index).concat(index.slice(index + 1));
}

Using the splice method

The splice method can remove an item from an array.
This example will mutate the original array.

function removeItem(items, itemToRemove) { 
   const index = items.indexOf(itemToRemove);
   items.splice(index,1);
   return items;
}

Using a for loop

This uses a for loop and constructs a new array containing everything you want to keep.

function removeItem(items, itemToRemove) { 
   const newArray = [];
   for (let I = 0; I < items.length; i++) {
      if (items[i] !== itemToRemove) {
        newArray.push(items[i]);
      }
   }
   return newArray;
}


© 2020 Better Solutions Limited. All Rights Reserved. © 2020 Better Solutions Limited TopPrevNext