LMX
BlogSelectedWorkSponsorsAbout
Command Palette

Search for a command to run...

Blog

Interviewer: Tell Me Every Array Method—Just the Basics

LMXApr 17, 202412 min read#JavaScript#Interview Notes

A summary of common JavaScript array methods for access, mutation, iteration, searching, and transformation, designed to strengthen practical knowledge and interview preparation.

Let me vent before we begin:

JavaScript has many array methods, but if someone suddenly asks you to name all of them, you probably cannot. That is the problem.

Then a tiny number of self-proclaimed frontend experts from major cities enter the room: “Have you even learned JavaScript? Why are your fundamentals so poor? Developers from smaller cities all have this problem—no foundation, career switchers lowering the bar, memorizing fancy interview trivia only at the last minute.”

That makes me want to swear.

We have to survive first. If we do not deliver projects, who will hire us? Not everyone spends every day building frontend infrastructure and studying a handful of APIs. We need to ship quickly and earn money. You may look down on us, but do not stand on the moral high ground to ridicule us. An interviewer like that lacks both decency and emotional intelligence. We all work for someone; why insist on ranking people into classes?

Still, I have plenty to improve myself. No use blaming others—keep working.

Accessing Array Elements

  • arr[index]: Get the element at an index.
  • arr.length: Get the array's length.

Modifying an Array

  • arr.push(item): Add an element to the end.

  • arr.pop(): Remove and return the last element.

  • arr.shift(): Remove and return the first element.

  • arr.unshift(item): Add an element to the beginning.

  • arr.splice(start, deleteCount, item1, item2, ...): Delete elements from a position and insert new elements.

    splice deserves a careful explanation—not because it is a common interview question, but because it is genuinely useful.

splice() is a powerful JavaScript array method for changing an array's contents. It can add, delete, or replace elements.

Syntax:

array.splice(start, deleteCount, item1, item2, ...);

Parameters:

  • start: Required. The index at which the operation begins.
  • deleteCount: Optional. The number of elements to remove. If omitted, every element from start through the end of the array is removed.
  • item1, item2, ...: Optional. New elements to insert at start.

Return value: A new array containing the removed elements.

There are too many APIs to memorize, so let us write a few examples.

Adding Elements

const numbers = [1, 2, 3];
// At index 2, delete 0 elements and add 4 and 5.
numbers.splice(2, 0, 4, 5);
console.log(numbers); // [1, 2, 4, 5, 3]

// You might expect index 2 with zero deletions to produce [1, 2, 3, 4, 5].
// To get that result, use numbers.splice(3, 0, 4, 5).
// Here start is 3, immediately after the final existing element,
// so insertion takes place at the end.

Deleting Elements

const numbers = [1, 2, 3, 4, 5];
// Starting at index 2, remove two elements.
numbers.splice(2, 2);
console.log(numbers); // [1, 2, 5]

Replacing Elements

const numbers = [1, 2, 3, 4, 5];
// Starting at index 2, remove two elements and insert 10.
numbers.splice(2, 2, 10);
console.log(numbers); // [1, 2, 10, 5]

Moving an Element to Another Position

const numbers = [1, 2, 3, 4, 5];
// Remove the first element and keep its value.
const firstElement = numbers.splice(0, 1)[0];
// Insert it at the target position.
numbers.splice(3, 0, firstElement);
console.log(numbers); // [2, 3, 4, 1, 5]

Joining Two Arrays

const numbers1 = [1, 2, 3];
const numbers2 = [4, 5, 6];
numbers1.splice(numbers1.length, 0, ...numbers2);
console.log(numbers1); // [1, 2, 3, 4, 5, 6]

Notes

  • splice() mutates the original array.
  • If start is greater than the array's length, insertion occurs at the end.
  • A negative deleteCount removes nothing.
  • Inserting more elements than you remove increases the length.
  • Inserting fewer elements than you remove decreases the length.

Iterating over an Array

  • for (let i = 0; i < arr.length; i++) { ... }: Iterate with a for loop.
  • for (const element of arr) { ... }: Iterate with for...of.
  • arr.forEach(callback): Iterate with forEach().

A forEach() iteration cannot be stopped with break; use a loop such as for...of when early termination is required.

Finding Elements

  • arr.indexOf(item): Return the first index of an element, or -1 if absent.

  • arr.lastIndexOf(item): Return the last index of an element, or -1 if absent.

  • arr.includes(item): Check whether an array contains an element.

    includes is particularly useful and deserves a closer look.

    includes() is a convenient way to determine whether a particular value is present without manually iterating over the array.

    Syntax:

    array.includes(searchElement, (fromIndex = 0));

    Parameters:

    • searchElement: Required. The value to find.
    • fromIndex: Optional. The index at which searching begins; defaults to 0.

    Return value: true if the value is found, otherwise false.

    const numbers = [1, 2, 3, 4, 5];
    const isPresent1 = numbers.includes(2); // true
    const isPresent2 = numbers.includes(6); // false
    
    const fruits = ["apple", "banana", "orange"];
    const isPresent3 = fruits.includes("banana", 1); // true
    const isPresent4 = fruits.includes("grape"); // false

    Limitations of includes(): It checks values using SameValueZero semantics and does not perform type coercion. The number 1 and string "1" therefore do not match. For condition-based searches, find() and findIndex() cover more everyday business cases.

  • arr.find(callback[, thisArg]): Return the first element satisfying a condition, or undefined if none does.

  • arr.findIndex(callback[, thisArg]): Return the index of the first satisfying element, or -1.

    find is especially common in application development:

    const numbers = [1, 2, 3, 4, 5];
    const evenNumber = numbers.find(function (number) {
      return number % 2 === 0;
    });
    console.log(evenNumber); // 2
    
    const fruits = ["apple", "banana", "orange"];
    const matchingFruit = fruits.find((fruit) => fruit.startsWith("o"));
    console.log(matchingFruit); // orange

Transforming Arrays

  • arr.join(separator): Join elements into a string with a separator.
  • arr.slice(start, end): Shallow-copy part of an array without changing the original.
  • arr.concat(array2, array3, ...): Join multiple arrays.
  • arr.sort(compareFunction): Sort an array.
  • arr.reverse(): Reverse an array. As its name suggests, it mutates the original.

Other Methods

The next three methods—map, filter, and reduce—are extremely practical.

map

map() transforms every element and creates a new array containing the callback's result for each original element.

array.map(callback[, thisArg]);

The required callback receives currentValue, currentIndex, and array. The optional thisArg becomes its this value. The method returns a new transformed array.

const numbers = [1, 2, 3, 4, 5];
const squaredNumbers = numbers.map(function (number) {
  return number * number;
});
console.log(squaredNumbers); // [1, 4, 9, 16, 25]

const fruits = ["apple", "banana", "orange"];
const upperCaseFruits = fruits.map((fruit) => fruit.toUpperCase());
console.log(upperCaseFruits); // ['APPLE', 'BANANA', 'ORANGE']

Advantages: concise, readable, and returns a new array without mutating the source.

Limitations: It performs one transformation per element and is not intended for accumulation.

  • Use forEach() when you need side effects but no returned array.
  • Use reduce() when you need to accumulate elements into one value.

filter

filter() creates a new array containing only elements that satisfy a condition.

array.filter(callback[, thisArg]);

The required callback receives currentValue, currentIndex, and array; thisArg is optional. The return value contains every element for which the callback returned a truthy value.

const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter(function (number) {
  return number % 2 === 0;
});
console.log(evenNumbers); // [2, 4]

const fruits = ["apple", "banana", "orange"];
const longFruits = fruits.filter((fruit) => fruit.length > 5);
console.log(longFruits); // ['banana', 'orange']

Advantages: concise, readable, and leaves the source array unchanged.

Limitations: It selects by one callback result; more involved operations may require combining methods.

  • Use find() or findIndex() when only the first match is needed.
  • Combine filter() with forEach() when an action must run for every matching element.

reduce

reduce() processes array elements in sequence and accumulates them into a single value, simplifying many otherwise complex operations.

array.reduce(callback[, initialValue]);

The callback receives four arguments:

  • accumulator: The previous callback result, or initialValue.
  • currentValue: The current element.
  • currentIndex: The current index.
  • array: The array being processed.

If initialValue is omitted, the first array element becomes the initial accumulator. The method returns the final accumulated value.

Sum all values:

const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce(function (accumulator, currentValue) {
  return accumulator + currentValue;
}, 0);
console.log(sum); // 15

Sum the even values:

const numbers = [1, 2, 3, 4, 5];
const evenSum = numbers.reduce(function (accumulator, currentValue) {
  if (currentValue % 2 === 0) {
    accumulator += currentValue;
  }
  return accumulator;
}, 0);
console.log(evenSum); // 6

Join elements into a string:

const words = ["hello", "world", "JavaScript"];
const sentence = words.reduce(function (accumulator, currentValue) {
  return accumulator + " " + currentValue;
}, "");
console.log(sentence); // hello world JavaScript

Group objects by a property:

const products = [
  { name: "apples", category: "fruits" },
  { name: "oranges", category: "fruits" },
  { name: "potatoes", category: "vegetables" },
];

const result = products.reduce((group, product) => {
  const { category } = product;
  group[category] = group[category] ?? [];
  group[category].push(product);
  return group;
}, {});

Advantages: concise and powerful for sums, averages, string assembly, grouping, and other accumulation.

Limitations: a complicated callback can reduce readability or become expensive. Prefer a clearer loop when it expresses the logic better.

  • Use forEach() for side effects without a returned value.
  • Use map() for one-to-one transformation into a new array.

Hello, brother. Welcome to the second installment of the Elevator Warrior series—Ding Qing. Leave a like, or I am coming for you.

Discussion

Support the author
Previous post

Improving Website Performance with Resource Hints

Next post

Intermediate Front-End Interview Compilation - Middle Volume

LMX BlogWeb · TypeScript · Vue · Node.js
Crafted by
@LMXZQQ
Build
unavailable
Date
2026-10-30
Articles
29
Deployed on
Nginx
Source code
GitHub
License
MIT License
Typeface
Geist
Stack
  • next@16.4.3
  • react@19.3.1
  • @base-ui/react@1.8.0
  • shadcn@4.12.0
  • tailwindcss@4.3.3
Analytics
  • OpenPanel
  • Google Analytics
For agents
  • llms.txt
  • index.md
Inspired by
  1. Tailwind CSS
  2. shadcn/ui
  3. Vercel
  4. Apple
  5. Evil Charts
  6. Devouring Details
  7. Skiper UI
  8. Making Software
  9. shadcncraft
Approved by
静水流深 / LMX
1602
Command Palette

Search for a command to run...