What I learned Today About Arrays And Objects In DSA.

What I learned Today About Arrays And Objects In DSA.

Learning arrays and objects in DSA.

What Are JavaScript Objects?

JavaScript objects store data as key-value pairs, like this:

const userProfile = {
name: "Ravi",
age: 28,
isAdmin: false
};

Unlike arrays, objects don’t care about order. You just access values directly using keys.

Why Are Objects So Fast?

When you’re addingaccessingupdating, or deleting data using keys, JavaScript objects are blazing fast. These actions take O(1) time, which means:

✅ Speed stays the same even if the object has 10 or 10,000 keys.

userProfile["age"]; // O(1) - Direct key access
userProfile["age"] = 30; // O(1) - Update
delete userProfile["isAdmin"]; // O(1) - Delete

🔍 Behind the scenes, JS uses a hash map mechanism to locate values instantly using keys.

But… Searching for a Value is Slow

Want to find if a value exists? Like:

// Does this object contain the value `true`?

Now JavaScript has to check every key-value pair one by one, so this takes O(n) time — much slower.

Object Methods: How Fast Are They?

Object.keys(obj)— Returns all keys — O(n)

Object.values(obj)— Returns all values — O(n)

Object.entries(obj)— Returns [key, value] pairs — O(n)

hasOwnProperty(key)— Checks if a key exists — O(1)

userProfile.hasOwnProperty("name"); // O(1) - Fast key check
Object.values(userProfile); // O(n) - Loops through all values

When Should You Use Objects?

Use objects if:

  • You need fast access using keys 🏎️
  • You don’t care about order
  • You don’t need to search for values often

Quick Notes: Big O Time for Object Tasks

Add / Update / Delete — O(1)

Access by Key — O(1)

Search by Value — O(n)

Object.keys()— O(n)

Object.values()— O(n)

Object.entries()— O(n)

hasOwnProperty()— O(1)

Arrays: Ordered 😀, but There’s a Catch 🤔

Arrays are JavaScript’s go-to structure when order matters.

const fruits = ["Apple", "Mango", "Banana"];
  • "Apple" is at index 0
  • "Mango" is at index 1
  • And so on…

✅ Great for ordered data
❗ But: that order can make some operations slow.

Big O Performance of Arrays

Access by index — O(1) — Direct lookup — super fast.

Add to end (push) — O(1) — Appends value at next index

Remove from end (pop) — O(1) — Just removes the last value

Add to start (unshift) — O(n) — Must shift all elements forward

Remove from start (shift) — O(n) — Must reindex everything

Search for value — O(n) — Checks each item until it finds a match

Accessing Elements — Blazing Fast

const planets = ["Mercury", "Venus", "Earth", "Mars"];
console.log(planets[2]); // Earth

Whether it’s index 0 or 9999 — still O(1) time.

Inserting or Removing Elements

Push — Fast

planets.push("Jupiter"); // O(1)

❌ Unshift — Slow

planets.unshift("Sun"); // O(n)

➡️ Every element gets shifted. Costly for large arrays.

❌ Shift — Also Slow

planets.shift(); // O(n)

➡️ Same problem — shifting everything back.

💡 Tip: Prefer push() and pop() over unshift() and shift() for performance.

Searching in an Array

const colors = ["Red", "Green", "Blue"];
colors.includes("Blue"); // O(n)

👀 JS checks each element one-by-one.
No shortcut unless it’s sorted, then you can use binary search later.

Quick Notes

arr[index]—O (1) — Direct access.

arr.push(val)— O(1) — Append at end

arr.pop()— O(1) — Remove last element

arr.unshift(val)— O(n) — Insert at start → all elements shift

arr.shift()— O(n) — Remove from start → all elements reindex

arr.includes(val)— O(n) — Scans the full array if needed

So

JavaScript arrays are great when you care about order.

But:

  • Be cautious with operations at the start of arrays.
  • Avoid unnecessary shift/unshift in performance-critical code.
  • Searching is slow (O(n)) unless the data is sorted.

Copying & Editing Methods

arr.slice(1, 3);         // O(n) → Creates a shallow copy
arr.splice(1, 1, "X"); // O(n) → Adds/removes in-place with shifts

⚠️ Performance scales with how much is copied or modified.

Iteration Methods: Also O(n)

These process each element one by one:

arr.map(fn)     // O(n)
arr.filter(fn) // O(n)
arr.reduce(fn) // O(n)
arr.forEach(fn) // O(n)

Each is powerful, but not “free” on large arrays.

sort() — The Slowest One Here

[5, 1, 8].sort(); // O(n log n)

Sorting requires many comparisons + swaps.

Avoid sort() in tight loops or big datasets without reason.

Note

slice()— O(n) — ️Copies part of the array

splice()— O(n) — ️Insert/remove in the middle

map()— O(n) — Iterates through each element

filter()— O(n) — Same as map, with conditions

reduce()— O(n) — Combines all elements

sort()— O(n log n) — Slowest — use carefully

One Line Summary

Objects are faster, but lack order. Arrays give order, with tradeoffs.

Leetcode Move Zeroes Problem

https://leetcode.com/problems/move-zeroes

One Approach (with splice)

var moveZeroes = function (nums) {
for (let i = nums.length - 1; i >= 0; i--) {
if (nums[i] === 0) {
nums.splice(i, 1); // O(n)
nums.push(0); // O(1)
}
}
};

👎 splice() inside a loop makes this O(n²)
Not ideal for large arrays.

Better Approach (O(n))

function moveZeroes(nums) {
let insertPos = 0;

for (let i = 0; i < nums.length; i++) {
if (nums[i] !== 0) {
nums[insertPos] = nums[i];
insertPos++;
}
}

while (insertPos < nums.length) {
nums[insertPos] = 0;
insertPos++;
}
}

✔️ Moves all non-zeroes first
✔️ Then fills the rest with zeros
✅ Time Complexity: O(n)
✅ Space Complexity: O(1) (in-place)

Thanks for reading!
— Ranjan

Leave a Comment

Your email address will not be published. Required fields are marked *