DEV Community

Tanuka Das
Tanuka Das

Posted on

12 Must Know Array Methods for the Next Interview - JavaScript

One thing common about every programmer, be it senior, junior, or entry-level we often look up syntaxes and methods while coding but it is not possible during an interview. Although many interviewers help and give hints if you get stuck, it is a good practice to have some of the methods memorized.

Array Methods

1.push() method is used to add items at the end of an array.

const books = ['Cracking the Coding Interview', 'C++ Without Fear'];
books.push('JavaScript');
books;

#Output: ['Cracking the Coding Interview', 'C++ Without Fear', 'JavaScript']

2.unshift() add values at beginning of the array.

books.unshift('');
books;

#Output: ['Cracking the Coding Interview', 'C++ Without Fear', 'JavaScript']

3..pop()removes the final element from the array.

const cartoons = ['Bugs Bunny', 'Scooby-Doo', 'Mickey Mouse', 'The Powerpuff Girls', 'Dora', 'Pooh']
cartoons.pop();

# 'Pooh'
certoons;

# Output: ['Bugs Bunny', 'Scooby-Doo', 'Mickey Mouse', 'The Powerpuff Girls', 'Dora']

4..shift() removes the very first element from the array.

const cartoons = ['Scooby-Doo', 'Mickey Mouse', 'The Powerpuff Girls', 'Dora', 'Pooh']
cartoons.shift();
# 'Bugs Bunny'
certoons;

# Output: ['Bugs Bunny', 'Scooby-Doo', 'Mickey Mouse', 'The Powerpuff Girls', 'Dora', 'Pooh']

5.The .slice() method, as the name implies, slices out a portion of the array. It doesn’t remove any element from the array, instead, it returns a copy of the original array.

const cartoons = ['Scooby-Doo', 'Mickey Mouse', 'The Powerpuff Girls', 'Dora', 'Pooh']
cartoons.slice();
certoons;

# Output: ['Scooby-Doo', 'Mickey Mouse', 'The Powerpuff Girls', 'Dora', 'Pooh']

.slice() method takes in two parameters, the index where the slice starts and the index before where the slice ends.

const cartoons = ['Scooby-Doo', 'Mickey Mouse', 'The Powerpuff Girls', 'Dora', 'Pooh']

cartoons.slice(1, 3);
# Output:['Mickey Mouse', 'The Powerpuff Girls']
If we pass in only one parameter, the .slice() method will slice from the given index to the end of the array. 
const cartoons = ['Scooby-Doo', 'Mickey Mouse', 'The Powerpuff Girls', 'Dora', 'Pooh']

cartoons.slice(2);
# Output: ['The Powerpuff Girls', 'Dora', 'Pooh']

6..splice()

The .splice() method is used to add, replace, and remove items to an array.

It can hold multiple parameters, the first refers to the index where the element will be placed. The second argument refers to the number of elements that will be removed. Every parameter after the first two defines the elements that should be added in the array.

Let’s take a look at the following example:

const cartoons = ['Scooby-Doo', 'Mickey Mouse', 'The Powerpuff Girls', 'Dora', 'Pooh']
// # 1
cartoons.splice(1, 0, 'SpongeBob');
// add 'SpongeBob' at index 1
// remove 0 elements
//Output: ['Scooby-Doo', 'SpongeBob', 'Mickey Mouse', 'The Powerpuff Girls', 'Dora', 'Pooh']
// # 2
cartoons.splice(4, 2, 'Patrick Star');
// add 'Patrick Star' at index 5
// remove 2 elements, starting at index 4, which is first given parameter
// Output: ['Scooby-Doo', 'SpongeBob', 'Mickey Mouse', 'The Powerpuff Girls', 'Patrick Star']
// # 3
cartoons.splice(2, 1);
// The item at index 2 will be removed as there aren't any defined parameter to replace it with
// remove 1 elements
// Output: ['Scooby-Doo', 'SpongeBob', 'The Powerpuff Girls', 'Patrick Star']

7..filter()

The .filter() method, pass in a callback function, which is called on each element in the array. It takes in the element as a parameter and returns a boolean value based on if the element should be included in the new array or not.

Let’s look at the following example:

const movies = [
  { name: 'Wonder Woman', year: 2017 },
  { name: 'Dark Phoenix', year: 2019 },
  { name: 'Spider-Man Homecoming', year: 2017 },
  { name: 'Avengers Endgame', year: 2019 },
  { name: 'The Dark Knight', year: 2008 }
]
const filterMovies = movies.filter((movie) => {
   return movie.year <= 2017 
})
//test filterMovie
console.log(filterMovies)
/*[
  { name: 'Wonder Woman', year: 2017 },
  { name: 'Spider-Man Homecoming', year: 2017 },
  { name: 'The Dark Knight', year: 2008 }
]*/

Here, the new array must include every movie that was released before or in 2017. So, when the filter method is called, it loops through the movies array and executes the callback function on each element in the array. If the element matches the boolean statement, it will add the element to the new array.

Note: The filter method doesn’t change the original array, only creates a new array.

8..map()

The .map() method maps through each element in the original array and converts it into a new array with all mapped elements. Let’s try to get every name from the movies array.

const movies = [
  { name: 'Wonder Woman', year: 2017 },
  { name: 'Dark Phoenix', year: 2019 },
  { name: 'Spider-Man Homecoming', year: 2017 },
  { name: 'Avengers Endgame', year: 2019 },
  { name: 'The Dark Knight', year: 2008 }
]
const moviesName = movies.map((movie) => {
   return movie.name 
})
console.log(moviesName)
// ['Wonder Woman', 'Dark Phoenix', 'Spider-Man Homecoming', 'Avengers Endgame', 'The Dark Knight']

Similar to the .filter() method, .map() takes in a callback function with a single parameter, and returns the new array with the elements we want, in this case, movie.name.

9..find()

The purpose of the .find() method is to find a single object in the array. It returns only the first element it can find that satisfice the provided condition.

const movies = [
  { name: 'Wonder Woman', year: 2017 },
  { name: 'Dark Phoenix', year: 2019 },
  { name: 'Spider-Man Homecoming', year: 2017 },
  { name: 'Avengers Endgame', year: 2019 },
  { name: 'The Dark Knight', year: 2008 }
]
const findMovie = movies.find((movie) => {
   return movie.name === 'Dark Phoenix'
})
//Output: { name: 'Dark Phoenix', year: 2019 }

10..forEach()

The .forEach() method is very similar to for loop but it takes in a function, and an argument, movie and for every single movie it will print out its name, movie.name.

const movies = [
  { name: 'Wonder Woman', year: 2017 },
  { name: 'Dark Phoenix', year: 2019 },
  { name: 'Spider-Man Homecoming', year: 2017 },
  { name: 'Avengers Endgame', year: 2019 },
  { name: 'The Dark Knight', year: 2008 }
]
movies.forEach((movie) => {
   console.log(movie.name)
})
// Wonder Woman
// Dark Phoenix
// Spider-Man Homecoming
// Avengers Endgame
// The Dark Knight

We get all the names of the movies; we can even print out the years, movie.year, or any other element from inside the array. This makes iterating through an array much easier and simpler.

11..reduce()

The .reduce() method runs a function on every element in the array and returns the reduced single value of the array. Let’s use a test score array for this example and retrieve the total score of all the different elements in the array.

const testScore = [
  { name: 'Ben',  score: 88 },
  { name: 'Joel', score: 98 },
  { name: 'Judy', score: 77 },
  { name: 'Anne', score: 88 },
  { name: 'Mike', score: 99 }
]
const filterMovies = testScore.reduce((currentTotal, score) => {
   return test.score + currentTotal
}, 0)
//Output: 450

The first method currentTotal, is the total after each iteration of the array and the second method score is the element we will be iterating through. The currentTotal will start at the very first iteration, at index 0 which we passed in as the second parameter.

The first time the reduce runs, we get 0, add that to Ben’s score, so 0 + 88 = 88. Now, 88 is the currentTotal, and the next element Joel’s score is the score value 98, 88+98= 186. 186 is the new currentTotal and it iterates until the very last score in the array. The output is 450, that’s the number we get after adding all the numbers.

12..includes()

The .include() method checks if an array has a certain value and returns true or false base on if the value present in the array. Let change up our example array for the very last time and use integers instead of objects.

const nums= [3, 8, 22, 45, 65, 99]
const includesNum = nums.includes(99) 
console.log(includesNum)
// output: true

This function checks to see if 99 is an element in the array. In this case, the output is true. If we change the value to 100, the output will be false because the array does not contain the value 100.

These are some of the array methods that I find very useful for interviews.

Top comments (9)

Collapse
 
starquest profile image
starquest • Edited

There's a bug in the .reduce() example. The second param for that method is the current item in the iterable. So for your example to work, it should be called score.score in the return statement.

Collapse
 
julians300 profile image
Julian Salas

It's worth noting, that .map, .filter and .reduce return a new array. The other methods mutate the array so keep that in mind in your next interview.

Collapse
 
tanuka16 profile image
Tanuka Das

Thanks!

Collapse
 
jonrandy profile image
Jon Randy 🎖️

I'd be dubious about working for a company that would give such a ridiculous coding interview

Collapse
 
mikelogaciuk profile image
mikelogaciuk

Quite strange for a job interview question :)

Collapse
 
tanuka16 profile image
Tanuka Das

I actually used the .map method on a code challenge last month and definitely used .slice, .pop, .push for many practice technical interview questions such as stack and queue.

Collapse
 
urielbitton profile image
Uriel Bitton

Very nice stuff! Also very useful for react

Collapse
 
tanuka16 profile image
Tanuka Das

Thanks :)

Collapse
 
phili0916 profile image
Philip Davis • Edited

This article is a great basis for understanding higher order array methods. Actually really helped me out a lot!