Array Operations | Deletion from Array | Explanation with Code | Data Structure at DSA using JavaScript

In the realm of Data Structures and Algorithms (DSA), arrays are one of the fundamental data types. They allow us to store a fixed-size sequential collection of elements of the same type. While inserting and accessing elements in an array is straightforward, deletion can be a bit more complex. In this article, we'll explore how to effectively delete elements from an array in JavaScript, along with practical code examples.

Understanding Array Deletion

Array deletion can occur in several ways, depending on the requirements. Here are the most common methods:

  1. Using splice() Method: This method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.
  2. Using filter() Method: This method creates a new array with all elements that pass the test implemented by the provided function.

Example 1: Deleting an Element Using splice()

let fruits = ['Apple', 'Banana', 'Cherry', 'Date'];
console.log('Original Array:', fruits);

// Deleting 'Banana' at index 1
fruits.splice(1, 1);
console.log('Array after deletion:', fruits);
        

Output:

Original Array: [ 'Apple', 'Banana', 'Cherry', 'Date' ]
Array after deletion: [ 'Apple', 'Cherry', 'Date' ]
        


Example 2: Deleting Elements Using filter()

let numbers = [1, 2, 3, 4, 5];
console.log('Original Array:', numbers);

// Deleting all even numbers
let filteredNumbers = numbers.filter(num => num % 2 !== 0);
console.log('Array after deletion of even numbers:', filteredNumbers);
        

Output:

Original Array: [ 1, 2, 3, 4, 5 ]
Array after deletion of even numbers: [ 1, 3, 5 ]
        

Conclusion

Array deletion is a crucial operation in data manipulation. Understanding how to effectively remove elements can optimize your algorithms and improve the overall efficiency of your code. By mastering methods like splice() and filter(), you can handle array modifications with ease.

Feel free to try out these methods in your projects and enhance your JavaScript skills!



#JavaScript #DataStructures #DSA #Coding #Programming #ArrayOperations #WebDevelopment #TechCommunity #LearnToCode

To view or add a comment, sign in

More articles by Navaneethan K V

Insights from the community

Others also viewed

Explore topics