DEV Community

Cover image for Mastering JavaScript Array Methods
MohitSinghChauhan
MohitSinghChauhan

Posted on • Originally published at mohitdotexe.hashnode.dev

Mastering JavaScript Array Methods

For many developers, arrays are the one data structure to rule them all. Arrays provide an intuitive way to organize ordered information and access it efficiently. But to truly unlock the power of arrays, you need to master the wide range of methods JavaScript provides.

JavaScript array methods are like magical incantations for manipulating arrays. With just a few lines of code, you can iterate, sort, map, join, filter, and reduce effortlessly. Forget messy for loops and complicated logic - these methods abstract away the complexity.

In this guide, you'll learn array syntax like the back of your hand. We'll explore all the essential methods for wrangling array data. Code examples demonstrate key concepts so you can quickly apply them in your own projects.

Take your JavaScript skills to the next level and learn to think like a true master of arrays! With the spells, I mean methods - we'll cover here, arrays will become an invaluable part of your toolbelt. Let's summon some arrays and get started!

Basic Methods

Let's start with some of the basic methods for manipulating arrays:

push()

The push() method appends a new element to the end of an array.

let fruits = ['apple', 'banana'];

fruits.push('orange'); 

// fruits is now ['apple', 'banana', 'orange']
Enter fullscreen mode Exit fullscreen mode

pop()

The pop() method removes the last element of an array.

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

let lastFruit = fruits.pop(); 

// lastFruit is 'orange'
// fruits is now ['apple', 'banana']
Enter fullscreen mode Exit fullscreen mode

unshift()

The unshift() method adds a new element to the beginning of an array.

let fruits = ['apple', 'banana'];

fruits.unshift('strawberry');

// fruits is now ['strawberry', 'apple', 'banana']
Enter fullscreen mode Exit fullscreen mode

shift()

The shift() method removes the first element of an array.

let fruits = ['strawberry', 'apple', 'banana'];

let firstFruit = fruits.shift();

// firstFruit is 'strawberry'
// fruits is now ['apple', 'banana']
Enter fullscreen mode Exit fullscreen mode

Iteration Methods

Next let's look at methods that iterate over arrays:

forEach()

The forEach() method executes a callback function on each element in an array.

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

fruits.forEach(fruit => {
  console.log(fruit);
});

// Logs: 
// apple
// banana  
// orange
Enter fullscreen mode Exit fullscreen mode

map()

The map() method returns a new array with the callback function applied to each element.

let numbers = [1, 2, 3]; 

let doubledNumbers = numbers.map(n => n * 2); 

// doubledNumbers is [2, 4, 6]
Enter fullscreen mode Exit fullscreen mode

filter()

The filter() method returns a new array with only elements that pass a condition inside the callback.

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

let evens = numbers.filter(n => n % 2 === 0);

// evens is [2, 4]
Enter fullscreen mode Exit fullscreen mode

reduce()

The reduce() method reduces the array to a single value, by calling the callback on each element.

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

let sum = numbers.reduce((accumulator, current) => {
  return accumulator + current;
}, 0);

// sum is 15
Enter fullscreen mode Exit fullscreen mode

some()

The some() method returns true if any element in the array passes the condition.

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

let hasEven = numbers.some(n => n % 2 === 0);

// hasEven is true
Enter fullscreen mode Exit fullscreen mode

every()

The every() method returns true only if all elements pass the condition.

let numbers = [2, 4, 6, 8];

let allEven = numbers.every(n => n % 2 === 0); 

// allEven is true
Enter fullscreen mode Exit fullscreen mode

find()

The find() method returns the first element that passes the condition.

let users = [
  {id: 1, name: 'John'},
  {id: 2, name: 'Sarah'},
  {id: 3, name: 'Mike'}
];

let user = users.find(user => user.id === 2);

// user is {id: 2, name: 'Sarah'}
Enter fullscreen mode Exit fullscreen mode

findIndex()

The findIndex() method returns the index of the first element that passes the condition.

let users = [
  {id: 1, name: 'John'},
  {id: 2, name: 'Sarah'},
  {id: 3, name: 'Mike'}  
];

let index = users.findIndex(user => user.id === 2);

// index is 1
Enter fullscreen mode Exit fullscreen mode

Joining and Splitting

There are also useful methods for joining and splitting arrays:

join()

The join() method creates a string from array elements, separated by a delimiter.

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

let fruitString = fruits.join(' and '); 

// fruitString is 'apple and banana and orange'
Enter fullscreen mode Exit fullscreen mode

split()

The split() method splits a string into an array based on a delimiter.

let fruitString = 'apple, banana, orange';

let fruits = fruitString.split(', ');

// fruits is ['apple', 'banana', 'orange']
Enter fullscreen mode Exit fullscreen mode

Other Helpful Methods

Here are a few more handy methods:

slice()

The slice() method returns a shallow copy of a portion of an array.

let fruits = ['apple', 'banana', 'orange', 'grapes'];

let citrus = fruits.slice(1, 3);

// citrus is ['banana', 'orange']
Enter fullscreen mode Exit fullscreen mode

splice()

The splice() method changes the contents of an array by removing and/or adding elements.

let fruits = ['apple', 'banana', 'orange', 'grapes'];

fruits.splice(2, 1, 'cherry');

// fruits is now ['apple', 'banana', 'cherry', 'grapes']
Enter fullscreen mode Exit fullscreen mode

concat()

The concat() method merges two or more arrays together.

let fruits = ['apple', 'banana'];
let citrus = ['orange', 'lemon'];

let produce = fruits.concat(citrus); 

// produce is ['apple', 'banana', 'orange', 'lemon']
Enter fullscreen mode Exit fullscreen mode

includes()

The includes() method checks if an array contains a value. Returns true or false.

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

let hasApple = fruits.includes('apple'); 

// hasApple is true
Enter fullscreen mode Exit fullscreen mode

Easter Eggs

Here are some array method tips that could come in handy:

  • Use map() instead of a for loop to avoid mutating the original array.

  • filter() can be used to remove null, undefined and false values from an array.

  • some() is short-circuiting - it stops iterating once it finds a match.

  • every() is short-circuiting - it stops iterating once it finds a non-match.

  • reduce() can be used to flatten nested arrays.

Conclusion

And there you have it - everything you need to know about JavaScript array methods! From joining strings to filtering data, these methods unlock the real power of arrays.

The key is to understand what each method does, and when to reach for it. Memorize this guide, play around with some examples, and arrays will become second nature. Soon you'll be able to refactor chunks of code into neat one-liners with methods like map, filter and reduce.

Mastering arrays is a milestone for any JavaScript developer. Use this guide as your reference whenever you need to manipulate ordered data. And just think - when you nail those array interview questions.

Don't forget to checkout my other blogs to become JS Wizard :) , I'll start JS Series soon to share more in-depth knowledge on JAVASCRIPT, Till then

Thanks for reading

Happy Coding ❤️

Top comments (9)

Collapse
 
ivorobioff profile image
Igor Vorobiov

reduce() is also useful for turning an array into an object

Collapse
 
mohitsinghchauhan profile image
MohitSinghChauhan • Edited

Yup, array of obj to obj, someone can think of wide range of it's use cases once someone understood it properly.

Collapse
 
abidullah786 profile image
ABIDULLAH786

Hey Igor Vorobiov!

Welcome to the community!

Absolutely, you're right! reduce() is indeed a handy method for returning object from an arrays objects.

const persons= [
{ id: 1, name: 'abidullah786' },
{ id: 2, name: 'Igor' },
{ id: 3, name: 'adam' }
];

const personsObject= persons.reduce((acc, person) => {
acc[person.id] = person.name;
return acc;
}, {});

console.log(personsObject);

// output
{
"1": "abidullah786",
"2": "Igor",
"3": "adam"
}

It's great to see you exploring JavaScript array methods. If you have any questions or need further insights, feel free to ask.

 
mohitsinghchauhan profile image
MohitSinghChauhan

Thanks for sharing, Glad to know that.

Collapse
 
mohitsinghchauhan profile image
MohitSinghChauhan

Thanks for sharing.

Collapse
 
x-cyl profile image
X-CYL

thanks for sharing , the essentialy methods. ;)

Collapse
 
mohitsinghchauhan profile image
MohitSinghChauhan

Thanks for reading! Have a wonderful day ahead 🎊

Collapse
 
tommyleong profile image
TommyLeong

Awesome content, thank you so much for sharing!

Collapse
 
mohitsinghchauhan profile image
MohitSinghChauhan

I'm glad you liked it, thanks for reading :)