Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for JavaScript Arrays: From Beginner to Advanced
keshav Sandhu
keshav Sandhu

Posted on

     

JavaScript Arrays: From Beginner to Advanced

Arrays are one of the most fundamental data structures in JavaScript, allowing developers to store and manipulate collections of values. Whether you're just getting started or looking to master more advanced array techniques, this guide will walk you through everything you need to know about JavaScript arrays.


1. What is an Array?

An array is a list-like object that stores multiple values under a single variable name. Each value (element) in an array has a numbered position, called itsindex, which starts from0.

letfruits=["Apple","Banana","Orange"];console.log(fruits[0]);// Output: "Apple"
Enter fullscreen modeExit fullscreen mode

2. Creating Arrays

Array Literals

The easiest way to create an array is using square brackets ([]):

letnumbers=[1,2,3,4,5];
Enter fullscreen modeExit fullscreen mode

Using theArray Constructor

You can also create an array using theArray constructor:

letarr=newArray(5);// Creates an empty array with length 5
Enter fullscreen modeExit fullscreen mode

3. Basic Array Operations

Add Elements

  • Push: Add an element to the end of an array.
letfruits=["Apple","Banana"];fruits.push("Orange");// ["Apple", "Banana", "Orange"]
Enter fullscreen modeExit fullscreen mode
  • Unshift: Add an element to the beginning.
fruits.unshift("Mango");// ["Mango", "Apple", "Banana"]
Enter fullscreen modeExit fullscreen mode

Remove Elements

  • Pop: Remove the last element.
fruits.pop();// Removes "Banana"
Enter fullscreen modeExit fullscreen mode
  • Shift: Remove the first element.
fruits.shift();// Removes "Mango"
Enter fullscreen modeExit fullscreen mode

4. Accessing and Modifying Elements

Each element in an array can be accessed using its index:

letcolors=["Red","Green","Blue"];console.log(colors[1]);// "Green"
Enter fullscreen modeExit fullscreen mode

You can also change the value at a specific index:

colors[2]="Yellow";// ["Red", "Green", "Yellow"]
Enter fullscreen modeExit fullscreen mode

5. Iterating Over Arrays

Usingfor Loop

letnumbers=[1,2,3];for(leti=0;i<numbers.length;i++){console.log(numbers[i]);}
Enter fullscreen modeExit fullscreen mode

UsingforEach Method

TheforEach method executes a function once for each element in the array:

numbers.forEach(num=>console.log(num));
Enter fullscreen modeExit fullscreen mode

6. Array Methods (Intermediate)

map

Themap method creates a new array by applying a function to each element.

letdoubled=[1,2,3].map(num=>num*2);// [2, 4, 6]
Enter fullscreen modeExit fullscreen mode

flatmap

The flatMap() method maps all array elements and creates a new flat array.

constmyArr=[1,2,3,4,5,6];constnewArr=myArr.flatMap(x=>[x,x*10]);// [1,10,2,20,3,30,4,40,5,50,6,60]
Enter fullscreen modeExit fullscreen mode

filter

Filters the array and returns only the elements that match the condition.

leteven=[1,2,3,4].filter(num=>num%2===0);// [2, 4]
Enter fullscreen modeExit fullscreen mode

reduce

Reduces the array to a single value by applying a function to each element.

letsum=[1,2,3,4].reduce((acc,num)=>acc+num,0);// 10
Enter fullscreen modeExit fullscreen mode

find

Returns the first element that matches a given condition.

letresult=[5,12,8,130,44].find(num=>num>10);// 12
Enter fullscreen modeExit fullscreen mode

includes

Checks if an array contains a specific element.

lethasApple=["Banana","Apple","Grapes"].includes("Apple");// true
Enter fullscreen modeExit fullscreen mode

7. Advanced Array Techniques

Spreading Arrays (...)

The spread operator (...) allows you to easily copy or combine arrays.

letarr1=[1,2,3];letarr2=[...arr1,4,5];// [1, 2, 3, 4, 5]
Enter fullscreen modeExit fullscreen mode

Array Destructuring

Array destructuring lets you unpack values from arrays into distinct variables.

let[first,second]=[10,20,30];console.log(first);// 10console.log(second);// 20
Enter fullscreen modeExit fullscreen mode

concat

Concatenates two or more arrays.

letarr1=[1,2];letarr2=[3,4];letcombined=arr1.concat(arr2);// [1, 2, 3, 4]
Enter fullscreen modeExit fullscreen mode

slice

Returns a shallow copy of a portion of an array.

letfruits=["Banana","Orange","Lemon","Apple"];letcitrus=fruits.slice(1,3);// ["Orange", "Lemon"]
Enter fullscreen modeExit fullscreen mode

splice

Adds/removes elements from an array.

letfruits=["Banana","Orange","Apple"];fruits.splice(1,0,"Lemon");// ["Banana", "Lemon", "Orange", "Apple"]
Enter fullscreen modeExit fullscreen mode

8. Multidimensional Arrays

Arrays can contain other arrays (also known as nested or multidimensional arrays).

letmatrix=[[1,2,3],[4,5,6],[7,8,9]];console.log(matrix[1][2]);// 6
Enter fullscreen modeExit fullscreen mode

9. Immutable Array Methods

Some array methods create new arrays without modifying the original array, which can be helpful in functional programming.

  • concat: Combines arrays without modifying the original ones.
  • map: Creates a new array based on the results of a function.
  • filter: Filters the array without changing the original array.

10. Sorting and Reversing

sort

Sorts the elements in an array:

letnums=[30,1,21,7];nums.sort((a,b)=>a-b);// [1, 7, 21, 30]
Enter fullscreen modeExit fullscreen mode

reverse

Reverses the elements in the array:

nums.reverse();// [30, 21, 7, 1]
Enter fullscreen modeExit fullscreen mode

11. Flattening Arrays

Flattening an array means reducing its dimensionality. You can use theflat method to flatten nested arrays.

letarr=[1,2,[3,4],[5,[6,7]]];console.log(arr.flat(2));// [1, 2, 3, 4, 5, 6, 7]
Enter fullscreen modeExit fullscreen mode

12. Removing Duplicates

You can use aSet to remove duplicates from an array:

letarr=[1,2,2,3,4,4];letuniqueArr=[...newSet(arr)];// [1, 2, 3, 4]
Enter fullscreen modeExit fullscreen mode

Conclusion

JavaScript arrays are a powerful tool for managing data in your applications. From basic operations like adding/removing elements to more advanced techniques like usingmap,reduce, andflat, arrays offer a wide range of functionality for developers at any skill level. Practice using these methods, and you'll soon master JavaScript arrays!

Top comments(2)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
mannuelf profile image
Mannuel
Hello world, building websites & web apps is my bag.
  • Location
    Oslo
  • Joined

flatMap() is cool too, have reached for it a few times.

CollapseExpand
 
keshav___dev profile image
keshav Sandhu
👋 Hi there! I'm a passionate developer with a love for solving challenging problems through code. I enjoy exploring new algorithms, optimizing solutions, and continuously learning about new techs.
  • Joined

yeah, will add it too thanks✨

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

👋 Hi there! I'm a passionate developer with a love for solving challenging problems through code. I enjoy exploring new algorithms, optimizing solutions, and continuously learning about new techs.
  • Joined

More fromkeshav Sandhu

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp