DEV Community

Avnish
Avnish

Posted on

Removing a Specific Item from an Array in JavaScript

Method 1: Using splice with indexOf

  1. Find the index of the item to remove using indexOf.
  2. Use splice to remove the element at that index.

The splice() method modifies the original array in place and optionally returns the removed elements.

const array = [2, 5, 9];
console.log("Original Array:", array);

// Find the index of the element to remove
const index = array.indexOf(5);

if (index > -1) { // Ensure the element exists
  array.splice(index, 1); // Remove one element at the found index
}

console.log("Updated Array:", array);
// Output: [2, 9]
Enter fullscreen mode Exit fullscreen mode

Method 2: Removing Single or Multiple Occurrences with Custom Functions

  1. Remove a Single Occurrence: Removes only the first instance of the specified value.
   function removeItemOnce(arr, value) {
       const index = arr.indexOf(value);
       if (index > -1) {
           arr.splice(index, 1);
       }
       return arr;
   }

   console.log(removeItemOnce([2, 5, 9, 5], 5));
   // Output: [2, 9, 5]
Enter fullscreen mode Exit fullscreen mode
  1. Remove All Occurrences: Removes all instances of the specified value from the array.
   function removeItemAll(arr, value) {
       let i = 0;
       while (i < arr.length) {
           if (arr[i] === value) {
               arr.splice(i, 1); // Remove the element
           } else {
               i++; // Move to the next element
           }
       }
       return arr;
   }

   console.log(removeItemAll([2, 5, 9, 5, 8, 5], 5));
   // Output: [2, 9, 8]
Enter fullscreen mode Exit fullscreen mode

Method 3: Functional Approach with filter

The filter() method creates a new array with all elements that pass the provided condition.

const array = [2, 5, 9, 5, 8, 5];

// Remove all occurrences of 5
const filteredArray = array.filter(item => item !== 5);

console.log(filteredArray);
// Output: [2, 9, 8]
Enter fullscreen mode Exit fullscreen mode

When to Use:

  • Use filter for immutability (it doesn't modify the original array).
  • Use splice if modifying the original array is acceptable.

TypeScript Version

In TypeScript, the same functions can ensure type safety:

function removeItem<T>(arr: T[], value: T): T[] {
    const index = arr.indexOf(value);
    if (index > -1) {
        arr.splice(index, 1);
    }
    return arr;
}

// Usage
console.log(removeItem([2, 5, 9], 5));
// Output: [2, 9]
Enter fullscreen mode Exit fullscreen mode

Key Takeaways

  1. splice: Removes elements in place but requires an index.
  2. filter: Creates a new array, ideal for immutability.
  3. Custom Functions: Provide flexibility to handle single or multiple occurrences.
  4. TypeScript: Use generic types for type-safe operations.

These methods cater to different needs and coding styles. Choose based on whether you want to modify the original array or work with a new one.

Top comments (0)