The Top Array & Object Methods for Interviews

1 min read

Your Guide to Modern JS Array and Object Methods

In many technical interviews, you'll be given a problem that involves manipulating data. For example: 'Take this array of user objects, filter out the admins, and return an array of just their names.'

Doing this with a for loop is the 'old' way. The 'modern' way is to use functional, chainable array methods.

Knowing these methods shows you write clean, modern, and readable JavaScript.

The 'Must-Know' Array Methods:

  • .map(): To transform each item in an array.
  • .filter(): To select a subset of items from an array.
  • .reduce(): To 'boil down' an array into a single value (e.g., a sum, or a new object).
  • .forEach(): To loop over an array (but it doesn't return anything).

The 'Must-Know' Object/ES6 Techniques:

  • Destructuring: To easily pull values out of objects and arrays.
  • Spread Operator (...): To easily copy or merge objects and arrays.

This cluster will cover these essential tools for data manipulation.

.map() vs. .forEach() vs. .filter()

Interview Question: 'What's the difference between .map(), .filter(), and .forEach()?'

This is a fundamental test of your array knowledge. Here's a simple breakdown.

The Data:

const numbers = [1, 2, 3, 4, 5];

1. .map() - To Transform

What it does: Creates a new array by running a function on every item in the original array. The new array has the same length as the original.

When to use it: When you want to transform data. 'I want a new array of these numbers, but doubled.'

const doubled = numbers.map((num) => {
  return num * 2;
});
// doubled is [2, 4, 6, 8, 10]
// numbers is still [1, 2, 3, 4, 5] (it's immutable)

2. .filter() - To Select

What it does: Creates a new array containing only the items that pass a test (i.e., the function returns true). The new array's length will be less than or equal to the original.

When to use it: When you want to select a subset of data. 'I want a new array with only the even numbers.'

const evens = numbers.filter((num) => {
  return num % 2 === 0;
});
// evens is [2, 4]
// numbers is still [1, 2, 3, 4, 5]

3. .forEach() - To Do Something

What it does: Executes a function for each item in the array. It returns undefined. It does not create a new array.

When to use it: When you just want to do something with each item, like print it to the console or save it to a database. It's for side effects.

const returnValue = numbers.forEach((num) => {
  console.log('Got number:', num);
});
// Console will log:
// 'Got number: 1'
// 'Got number: 2'
// 'Got number: 3'
// 'Got number: 4'
// 'Got number: 5'
// 
// returnValue is 'undefined'

The simple answer: '.map() transforms each item and returns a new array. .filter() selects items that pass a test and returns a new array. .forEach() just loops over the items and returns undefined; it's for side effects.'

.reduce(): Your Most Powerful Array Method

Interview Question: 'Can you explain .reduce()?'

.reduce() is often seen as the most complex array method, but it's incredibly powerful. It's the 'Swiss Army knife' of array methods.

Answer: 'The .reduce() method runs a 'reducer' function on each item in an array to 'boil it down' into a single value. This single value can be anything: a number, a string, an object, or even another array.'

It takes two arguments:

  1. A callback function (the 'reducer').
  2. An initial value (the starting point).

The reducer callback itself takes two main arguments: the accumulator (the value built up so far) and the currentValue (the current array item).


Example 1: Summing an Array (Simple)

This is the 'Hello World' of .reduce().

const numbers = [1, 2, 3, 4, 5];

// The 'accumulator' is 'sum'
// The 'currentValue' is 'num'
// 0 is the 'initial value'
const total = numbers.reduce((sum, num) => {
  return sum + num;
}, 0);

// How it works:
// Pass 1: sum=0, num=1. Returns 1.
// Pass 2: sum=1, num=2. Returns 3.
// Pass 3: sum=3, num=3. Returns 6.
// Pass 4: sum=6, num=4. Returns 10.
// Pass 5: sum=10, num=5. Returns 15.

// total is 15

Example 2: Grouping by a Property (Advanced)

This is a common interview problem. 'Take this array of objects and turn it into an object, grouped by category.'

const food = [
  { name: 'Apple', category: 'Fruit' },
  { name: 'Carrot', category: 'Vegetable' },
  { name: 'Banana', category: 'Fruit' },
  { name: 'Broccoli', category: 'Vegetable' },
];

// The 'initial value' is an empty object: {}
const groupedFood = food.reduce((acc, item) => {
  const category = item.category;
  
  // If this category isn't an array in our accumulator yet, create it
  if (!acc[category]) {
    acc[category] = [];
  }
  
  // Push the current item into its category's array
  acc[category].push(item);
  
  // Always return the accumulator for the next pass
  return acc;
}, {});

console.log(groupedFood);
// Output:
// {
//   Fruit: [ { name: 'Apple', ... }, { name: 'Banana', ... } ],
//   Vegetable: [ { name: 'Carrot', ... }, { name: 'Broccoli', ... } ]
// }

You can solve almost any array transformation with .reduce().

Deep Dive: Object Destructuring and the Spread Operator

Interview Question: 'What is destructuring and the spread operator?'

These are two of the most-loved ES6 features. They are 'syntactic sugar' for making your code more concise and readable when working with objects and arrays.


1. Destructuring: Pulling Data Out

Destructuring is a clean syntax for 'unpacking' values from an object or array into distinct variables.

'Before' (Old Way):

const user = {
  id: 123,
  firstName: 'Alice',
  email: '[email protected]'
};

const firstName = user.firstName;
const email = user.email;
console.log(firstName, email); // 'Alice', '[email protected]'

'After' (Destructuring):

const user = {
  id: 123,
  firstName: 'Alice',
  email: '[email protected]'
};

// Pull 'firstName' and 'email' out into variables of the same name
const { firstName, email } = user;
console.log(firstName, email); // 'Alice', '[email protected]'

// You can even rename variables and set default values!
const { firstName: fName, status = 'active' } = user;
console.log(fName); // 'Alice'
console.log(status); // 'active'

2. Spread Operator (...): Pulling Data In

The Spread Operator (...) looks similar but does the opposite. It 'spreads' the properties of one object or array into a new object or array. It's the easiest way to make shallow copies and merge objects.

Example: Copying an Array (Immutability)

const original = ['a', 'b', 'c'];

// Create a new array, spreading in the items from the original
const copy = [...original];

copy.push('d');

console.log(copy); // ['a', 'b', 'c', 'd']
console.log(original); // ['a', 'b', 'c'] (unchanged!)

Example: Merging Objects (Creating a new object)

const user = { id: 123, name: 'Alice' };
const profile = { email: '[email protected]', city: 'NYC' };

// Create a new object by spreading in two others
const combined = { ...user, ...profile };

// { id: 123, name: 'Alice', email: '[email protected]', city: 'NYC' }
console.log(combined);

// It can also be used to 'override' properties
const updated = { ...combined, city: 'London' };
// { id: 123, name: 'Alice', email: '[email protected]', city: 'London' }
console.log(updated);

Bonus: The Spread Operator (...) can also be used in function arguments, where it's called the Rest Operator. It 'gathers' all remaining arguments into an array.

💬