Web Development Handbook

Web Development Handbook

Development is fun in a funny way

JavaScript Array Methods for Beginners

JavaScript Array Methods for Beginners

0 votes
0 votes
0 comments
351 views
Share

By Nihar Ranjan Das, Published on May 13th 2023 | 18 mins, 1775 words

In JavaScript, arrays are one of the most powerful and versatile features of the language. They can be used to store a variety of data types, including strings, numbers, objects, and even other arrays. Arrays also have a wide range of methods that can be used to manipulate their contents.

In this article, we will discuss the most important JavaScript array methods. We will cover how to use each method, as well as provide some examples of how they can be used in real-world applications.

Here are some of the most important JavaScript array methods:

  • forEach
  • map
  • filter
  • reduce
  • reduceRight
  • every
  • some
  • indexOf
  • lastIndexOf
  • join
  • slice
  • splice
  • reverse
  • sort
  • copyWithin
  • fill
  • entries
  • keys
  • values
  • from
  • of


These methods can be used to perform a variety of tasks, such as:

  • Iterating over the elements of an array
  • Creating a new array with the results of a function applied to each element of the original array
  • Selecting elements from an array that meet certain criteria
  • Combining the elements of an array into a single value
  • Reversing the order of the elements in an array
  • Sorting the elements in an array
  • And much more!

By learning how to use JavaScript array methods, you can greatly improve your ability to write efficient and effective JavaScript code.

Let's dive into and learn 

forEach

The forEach method is used to execute a callback function for each element in the array. The callback function takes the current element as its only argument.

const fruits = ['apple', 'banana', 'orange'];

fruits.forEach(function(fruit) {
  console.log(fruit);
});

This code will print the following to the console:

apple
banana
orange


map

The map method is used to create a new array with the results of calling a callback function for each element in the original array. The callback function takes the current element as its only argument and returns the new value for that element.

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

const squares = numbers.map(function(number) {
  return number * number;
});

This code will create a new array called squares with the following elements:

This code will print the following to the console:

1
4
9
16
25


filter

The filter method is used to create a new array with the elements of the original array that pass a certain test. The test is a callback function that takes the current element as its only argument and returns a Boolean value.

const fruits = ['apple', 'banana', 'orange', 'grape', 'cherry'];

const citrusFruits = fruits.filter(function(fruit) {
  return fruit.startsWith('c');
});

This code will create a new array called citrusFruits with the following elements:

This code will print the following to the console:

'apple'
'orange'


reduce

The reduce method is used to reduce the array to a single value by combining the elements using a callback function. The callback function takes two arguments: the current accumulator value and the current element. The accumulator value is initialized to the value of the first element in the array.

const prices = [10, 20, 30, 40, 50];

const totalPrice = prices.reduce(function(accumulator, price) {
  return accumulator + price;
});

console.log(totalPrice);

This code will calculate the total price of all the items in the prices array. The total price will be stored in the variable totalPrice.

This code will print the following to the console:

150


reduceRight

The reduceRight method is similar to the reduce method, but it starts combining the elements from the end of the array.

const words = ['This', 'is', 'a', 'sentence'];

const reversedSentence = words.reduceRight(function(accumulator, word) {
  return accumulator + word;
});

console.log(reversedSentence);

This code will reverse the order of the words in the words array and store the result in the variable reversedSentence.

This code will print the following to the console:

sentenceaisThis


every

Every method is used to test if all of the elements in the array pass a certain test. The test is a callback function that takes the current element as its only argument and returns a Boolean value.

const isEven = function(number) {
  return number % 2 === 0;
};

const allEven = [2, 4, 6, 8].every(isEven);


This code will check if all of the elements in the allEven array are even. The code will return true because all of the elements in the array are even.

This code will print the following to the console:

true


some

The some method is used to test if any of the elements in the array pass a certain test. The test is a callback function that takes the current element as its only argument and returns a Boolean value.

const isGreaterThanTen = function(number) {
  return number > 10;
};
const anyGreaterThanTen = [1, 2, 3, 11, 15, 9].some(isGreaterThanTen);

console.log(anyGreaterThanTen);

This code will print the following to the console:

11
15


indexOf

The indexOf() method is a JavaScript method that is used to find the index of a specified value in an array. The indexOf() method takes two arguments: the value to search for and the start index. The start index is optional and defaults to 0.

If the value is found in the array, the indexOf() method returns the index of the value. If the value is not found in the array, the indexOf() method returns -1.

const fruits = ['apple', 'banana', 'orange'];
const index = fruits.indexOf('apple');

console.log(index);

Will output the following:

0


lastIndexOf

The lastIndexOf() method is a JavaScript method that is used to find the index of the last occurrence of a specified value in an array. The lastIndexOf() method takes two arguments: the value to search for and the start index. The start index is optional and defaults to the length of the array minus 1.

If the value is found in the array, the lastIndexOf() method returns the index of the value. If the value is not found in the array, the lastIndexOf() method returns -1.

const fruits = ['apple', 'banana', 'orange'];
const index = fruits.lastIndexOf('kiwi');

console.log(index);

Will output the following:

-1


join

The join() method returns a string that is the result of joining all of the elements of the array, separated by the specified separator. The separator can be a string, a number, or an object. If no separator is specified, the elements of the array will be joined by a comma.

For example, the following code:

const fruits = ['apple', 'banana', 'orange'];
const joinedFruits = fruits.join(', ');

console.log(joinedFruits);

Will output the following:

apple, banana, orange


slice

The slice() method returns a new array that contains a portion of the original array. The slice() method takes three arguments: the start index, the end index, and the optional step value. The start index is the index of the first element to be included in the new array. The end index is the index of the last element to be included in the new array. The step value is the number of elements to skip between each element in the new array.

For example, the following code:

const fruits = ['apple', 'banana', 'orange', 'grape', 'cherry'];
const newFruits = fruits.slice(1, 3);

console.log(newFruits);

Will output the following:

banana, orange]


splice

The splice() method changes the contents of an array by removing and/or adding elements. The splice() method takes three or four arguments: the start index, the number of elements to remove, and the optional elements to add. The start index is the index of the first element to be removed. The number of elements to remove is the number of elements to be removed from the array. The optional elements to add are the elements to be added to the array.

For example, the following code:

const fruits = ['apple', 'banana', 'orange', 'grape', 'cherry'];
fruits.splice(1, 2, 'mango');

console.log(fruits);

Will output the following:

[apple, mango, orange, grape, cherry]


reverse

The reverse() method reverses the order of the elements in an array.

For example, the following code:

const fruits = ['apple', 'banana', 'orange'];
fruits.reverse();

console.log(fruits);

Will output the following:

[orange, banana, apple]


sort

The sort() method sorts the elements of an array in place. The default sort order is ascending, but you can specify a different sort order by passing a function as the first argument to the sort() method. The function must take two arguments and return a negative number, zero, or a positive number, depending on whether the first argument is less than, equal to, or greater than the second argument.

For example, the following code:

const fruits = ['apple', 'banana', 'orange'];
fruits.sort();

console.log(fruits);

Will output the following:

['apple', 'banana', 'orange']


copyWithin

The copyWithin() method copies a portion of an array to a different location in the array. The copyWithin() method takes four arguments: the start index, the end index, the source index, and the optional target index. The start index is the index of the first element to be copied. The end index is the index of the last element to be copied. The source index is the index of the element in the source array that will be copied to the destination array. The target index is the index of the element in the destination array that will be overwritten by the copied element.

For example, the following code:

const fruits = ['apple', 'banana', 'orange'];
fruits.copyWithin(1, 2, 0);

console.log(fruits);

Will output the following:

['banana', 'apple', 'orange']


fill

The fill() method fills an array with a specified value. The fill() method takes two arguments: the value to fill the array with, and the optional start index. The start index is the index of the first element to be filled. If no start index is specified, the fill operation will start at the beginning of the array.

For example, the following code:

const fruits = ['apple', 'banana', 'orange'];
fruits.fill('*'); 

console.log(fruits);

Will output the following:

['*', '*', '*']


entries

The entries() method returns an array of arrays, where each inner array contains the key and value of each element in the original array.

For example, the following code:

const fruits = ['apple', 'banana', 'orange'];
const entries = fruits.entries();

console.log(entries);

Will output the following:

[
    [0, 'apple'], 
    [1, 'banana'], 
    [2, 'orange']
]


keys

The keys() method returns an array of the keys of the original array.

For example, the following code:

const fruits = ['apple', 'banana', 'orange'];
const keys = fruits.keys();

console.log(keys);

Will output the following:

[0, 1, 2]


values

The values() method returns an array of the values of the original array.

For example, the following code:

const fruits = ['apple', 'banana', 'orange'];
const values = fruits.values();

console.log(values);

Will output the following:

['apple', 'banana', 'orange']


from

The from() method creates a new array from an iterable object. The from() method takes one argument: the iterable object. The iterable object can be an array, an object, a string, or a generator function.

For example, the following code:

const fruits = ['apple', 'banana', 'orange'];
const newFruits = Array.from(fruits);

console.log(newFruits);

Will output the following:

['apple', 'banana', 'orange']


of

The of() method creates a new array with the specified elements. The of() method takes one or more arguments, each of which is the element to be added to the array.

For example, the following code:

const fruits = Array.of('apple', 'banana', 'orange');

console.log(fruits);

Will output the following:

['apple', 'banana', 'orange']


If you like our tutorial, do make sure to support us by buy us a coffee ☕️

Comments

Default avatar

Are you interested to learn more?

Be notified on future content. Never spam.