Lesson 38: Mastering JavaScript Array Methods with challenges!

manoj ymkmanoj ymk
6 min read

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:

CategoryMethods
Add/Remove Itemspush, pop, shift, unshift, splice
SearchindexOf, lastIndexOf, includes, find, findIndex, filter
Transform/IterateforEach, map
Slice/Concatenateslice, concat

2. Fill Any Gaps

  • Mutation vs Non-mutation:
    push, pop, shift, unshift, and splice change the original array. slice, map, filter, reduce, concat, every, some do not mutate the original array.

  • splice and slice confusion:
    splice(start, deleteCount, items...) mutates by removing/inserting elements.
    slice(start, end) copies elements and returns a new array.

  • map vs forEach:
    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 find NaN.
    includes returns true if an element is present and can detect NaN.
    find and findIndex 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

  1. Write a function that returns a new array with only the even numbers from a given array.

  2. Given an array of strings, create a new array with all strings converted to uppercase using an array method.

  3. Implement a function that takes an array and returns the sum of all its numeric elements using reduce.

  4. Create a function that removes all null and undefined values from an array using filter.

🟡 Intermediate

  1. Write a function that takes an array of numbers and returns an array of their squares, but excludes numbers greater than 50 after squaring.

  2. Given an array of objects representing people {name, age}, return the name of the oldest person using array methods.

  3. Implement a function that flattens a two-dimensional array into a one-dimensional array using reduce and concat.

  4. 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

  1. 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}).

  2. Implement a function that mimics Array.prototype.reduceRight without using the built-in method.

🎯 Brain-Twister / “Aha!” Problem

  1. 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, and reduce in terms of input, output, and use cases?

  • How does find differ from filter? Can you provide an example scenario for each?

  • Why might you prefer slice over splice 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 versus includes to find NaN 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, and filter

  • Search features: Implementing live search with filter and includes

  • 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:

MnemonicMethodsBehavior
PUSH & POP: Stackpush(), pop()Add/remove from end (mutate)
SHIFT & UNSHIFT: Queueshift(), unshift()Add/remove from start (mutate)
SLICE: Copyslice()Extract copy (non-mutating)
SPLICE: Editsplice()Insert/remove (mutates)
MAP: Transformmap()Returns new array with changes
FILTER: Selectfilter()Returns subset array
REDUCE: Aggregatereduce()Returns single value
FIND: Searchfind(), findIndex()Returns first matching element/index
INCLUDES/INDEXOFincludes(), 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 of undefined)

    • 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 declaratively

    • Lodash extends native arrays with methods like _.flatten, _.uniq, _.chunk for convenience

0
Subscribe to my newsletter

Read articles from manoj ymk directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

manoj ymk
manoj ymk