Labs ICT
Pro Login

Array Operations

Insert, delete, search, and traverse.

Array Operations

Alright, let's talk about what you can actually do with arrays. Every data structure has its moves, and arrays are no different. Understanding these operations and their time complexities will make you a better developer, trust me.

The key thing to remember is that insertion and deletion locations matter a lot. Adding to the end is cheap, but adding to the beginning? That's expensive because everything has to shift. It's all about trade-offs in programming.

Insert Operations

Inserting at the end is O(1) - just slap it on. But inserting at the beginning? That's O(n) because every single element needs to move one position to the right. Same story for inserting in the middle - everything after that point shifts.

Think of it like a concert line. Adding someone at the back is easy, but inserting someone at the front means everyone has to move. Nobody likes that person.

const arr = [1, 2, 3, 4, 5];
arr.push(6);
arr.unshift(0);
arr.splice(2, 0, 99);
console.log(arr);

Delete Operations

Deletion works the same way - removing from the end is O(1), but removing from the beginning or middle requires shifting elements back. It's the inverse of insertion. The further back you remove, the more work the computer has to do.

pop() removes from the end, shift() removes from the beginning, and splice() lets you remove from any position. Choose wisely based on your performance needs.

const nums = [10, 20, 30, 40, 50];
nums.pop();
nums.shift();
nums.splice(1, 2);
console.log(nums);

Search Operations

For searching, you have two options. If the array is unsorted, you're stuck with linear search O(n) - checking each element one by one. But if it's sorted, binary search O(log n) is your friend, cutting the search space in half each time.

indexOf() and includes() are your go-to methods for finding elements. They're simple and work well for small arrays. For larger datasets, consider sorting first and using binary search.

const fruits = ["apple", "banana", "cherry"];
const index = fruits.indexOf("banana");
const hasApple = fruits.includes("apple");
const found = fruits.find(f => f.startsWith("b"));
console.log(index, hasApple, found);

Traversal Patterns

Traversing arrays is something you'll do constantly. For loops, while loops, forEach, map - they all work. The key is picking the right pattern for your use case.

Use for loops when you need the index, forEach for simple operations, and map when you want to transform the array. Each pattern has its place, and knowing when to use each one makes your code cleaner and more efficient.

const nums2 = [1, 2, 3, 4, 5];
for (let i = 0; i < nums2.length; i++) {
  console.log(nums2[i]);
}
nums2.forEach(n => console.log(n * 2));
const doubled = nums2.map(n => n * 2);
console.log(doubled);
Try it Yourself →