Lesson 38: Mastering JavaScript Array Methods with challenges!

Array methods in JavaScript are built-in functions available on Array objects. They allow you to perform common operations such as adding, removing, searching, iterating, transforming, and slicing arrays efficiently. Some methods mutate the original array (like splice
, push
), while others return new arrays or values (like map
, filter
, reduce
). These methods provide expressive, declarative ways to work with list-like data.
🔧 Categories of Array Methods:
Category | Methods |
Add/Remove Items | push , pop , shift , unshift , splice |
Search | indexOf , lastIndexOf , includes , find , findIndex , filter |
Transform/Iterate | forEach , map |
Slice/Concatenate | slice , concat |
2. Fill Any Gaps
Mutation vs Non-mutation:
push
,pop
,shift
,unshift
, andsplice
change the original array.slice
,map
,filter
,reduce
,concat
,every
,some
do not mutate the original array.splice
andslice
confusion:
splice(start, deleteCount, items...)
mutates by removing/inserting elements.
slice(start, end)
copies elements and returns a new array.map
vsforEach
:
map
returns a new array based on the callback's return values.forEach
just runs a callback on each item, returning nothing.Searching differences:
indexOf
uses strict equality (===
) and fails to findNaN
.
includes
returns true if an element is present and can detectNaN
.
find
andfindIndex
accept callback predicates for flexible searching.reduce
versatility:
Used to aggregate array items into a single value (sum, product, concatenation, object).Shallow copying:
Many methods (slice
,map
,filter
) create shallow copies—nested objects/arrays remain referenced.
3. Challenge Me Deeply (Array Methods)
10 Coding Challenges (increasing difficulty, different angles, no solutions):
🟢 Basic
Write a function that returns a new array with only the even numbers from a given array.
Given an array of strings, create a new array with all strings converted to uppercase using an array method.
Implement a function that takes an array and returns the sum of all its numeric elements using
reduce
.Create a function that removes all
null
andundefined
values from an array usingfilter
.
🟡 Intermediate
Write a function that takes an array of numbers and returns an array of their squares, but excludes numbers greater than 50 after squaring.
Given an array of objects representing people
{name, age}
, return the name of the oldest person using array methods.Implement a function that flattens a two-dimensional array into a one-dimensional array using
reduce
andconcat
.Create a function that groups an array of strings by their first letter and returns an object where keys are letters and values are arrays of strings starting with that letter.
🔴 Advanced
Write a function that takes an array of mixed data types and returns an object with counts of each type (e.g.,
{number: 3, string: 5, boolean: 2}
).Implement a function that mimics
Array.prototype.reduceRight
without using the built-in method.
🎯 Brain-Twister / “Aha!” Problem
- Given an array of integers, find the length of the longest subarray where the difference between the max and min elements is at most 1, using array methods only (no loops).
4. Interview-Ready Questions (Array Methods)
Concept-Based
Explain the difference between mutating and non-mutating array methods with examples.
What are the differences between
map
,filter
, andreduce
in terms of input, output, and use cases?How does
find
differ fromfilter
? Can you provide an example scenario for each?Why might you prefer
slice
oversplice
when working with arrays in immutable programming?
Scenario-Based
How would you remove duplicate elements from an array efficiently? What array methods would you use and why?
You have a large array of user objects, and you want to update the age of a particular user immutably. How would you do it with array methods?
How can you convert an array of numbers into a comma-separated string, and what method would you use?
Debugging-Style
Consider this code snippet:
const arr = [1, 2, 3, 4, 5]; const result = arr.map(num => { if (num % 2 === 0) { return num * 2; } }); console.log(result);
What will be logged and why? How can this be fixed?
Given the following code:
const arr = [10, 20, 30, 40]; arr.splice(2, 1); console.log(arr);
What will be the output? Does
splice
mutate the array or return a new one?What is the difference in behavior when using
indexOf
versusincludes
to findNaN
in an array? Why does it happen?
5. Real-World Usage
Filtering user input: Removing empty strings or invalid entries with
filter
Mapping data: Transforming API response data into UI-friendly formats using
map
Summarizing data: Using
reduce
to calculate totals, averages, or aggregates (e.g., shopping cart totals)State management: Updating arrays immutably in frameworks like React using
slice
,concat
,map
, andfilter
Search features: Implementing live search with
filter
andincludes
Pagination: Using
slice
to grab a page of items from a large array
6. Remember Like a Pro
Mnemonic to remember common array methods and their behavior:
Mnemonic | Methods | Behavior |
PUSH & POP: Stack | push() , pop() | Add/remove from end (mutate) |
SHIFT & UNSHIFT: Queue | shift() , unshift() | Add/remove from start (mutate) |
SLICE: Copy | slice() | Extract copy (non-mutating) |
SPLICE: Edit | splice() | Insert/remove (mutates) |
MAP: Transform | map() | Returns new array with changes |
FILTER: Select | filter() | Returns subset array |
REDUCE: Aggregate | reduce() | Returns single value |
FIND: Search | find() , findIndex() | Returns first matching element/index |
INCLUDES/INDEXOF | includes() , indexOf() | Boolean/position check |
7. Apply It in a Fun Way
Build a Tiny Todo List Using Array Methods
class TodoList {
constructor() {
this.todos = [];
}
add(todo) {
this.todos.push(todo); // add at end
}
remove(task) {
this.todos = this.todos.filter(t => t !== task); // remove matching task(s)
}
markDone(task) {
this.todos = this.todos.map(t => (t === task ? t + ' ✅' : t)); // mark done
}
list() {
this.todos.forEach((t, i) => console.log(`${i + 1}: ${t}`)); // display tasks
}
}
const todo = new TodoList();
todo.add('Learn JS Array methods');
todo.add('Build a project');
todo.markDone('Learn JS Array methods');
todo.list();
This demonstrates push
, filter
, map
, and forEach
in an easy, real-world style.
Bonus: Common Mistakes, Performance Tips & Open Source Use
Common Mistakes:
Using
map
without returning a value (results in array ofundefined
)Assuming
splice
returns a new array (it returns removed elements)Not handling sparse arrays when iterating
Performance Tips:
Avoid chaining heavy array methods repeatedly in hot code (cache intermediate results)
Prefer loops over some methods in performance-critical contexts (though most engines optimize well)
Open Source Usage:
React uses
map
to render lists of components declarativelyLodash extends native arrays with methods like
_.flatten
,_.uniq
,_.chunk
for convenience
Subscribe to my newsletter
Read articles from manoj ymk directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
