storieasy-logo

JavaScript Array Methods: A Complete and Detailed Guide

milan

Milan Patel

6 Jun 2025

|

30 min to read

js-arrays-method

arraymethods

JavaScriptArrays

JavaScript

ModernJavaScript

array

ArrayTips

LearnToCode

Learn all JavaScript array methods with detailed, up-to-date examples. From beginner basics to advanced transformations, master JS arrays

🧾 What is an Array in JavaScript?

An array in JavaScript is a special object used to store ordered collections of items, like numbers, strings, objects, or even other arrays. Arrays are dynamic and can grow or shrink, making them one of the most commonly used data structures in the language.

1const fruits = ['apple', 'banana', 'cherry'];

πŸ”Ή 1. Creating Arrays

βœ… Array.of()

This makes a new array with the values you give.

➀ Example:

1const arr2 = Array.of(1, 2, 3);
2console.log(arr2); // [1, 2, 3]

βœ… Array.from()

This turns other things (like strings or lists) into arrays.

➀ Example 1: Turn a string into an array of letters

1const word = 'hello';
2const letters = Array.from(word);
3console.log(letters); // ['h', 'e', 'l', 'l', 'o']

➀ Example 2: Turn a set into an array

1const mySet = new Set([1, 2, 2, 3]);
2const arr = Array.from(mySet);
3console.log(arr); // [1, 2, 3]

➀ Example 3: Create and change values at the same time

1const numbers = Array.from([1, 2, 3], x => x * 2);
2console.log(numbers); // [2, 4, 6]

πŸ” 2. Iteration Methods in JavaScript (Easy & Explained)

JavaScript arrays come with iteration methods that let you loop through each item and do something with it. These methods make your code cleaner, faster, and easier to read.

πŸ” forEach() – Do something with each item

This method runs a function for each item in the array.
But it doesn’t return a new array.

➀ Example:

1const numbers = [1, 2, 3];
2numbers.forEach(num => {
3  console.log(num);
4});
5// Output: 1  2  3

Use this when you just want to print or perform actions with each item, but don’t need a new array.

πŸ”„ map() – Change each item and return a new array

This creates a new array by changing every item in the original one.

➀ Example:

1const nums = [1, 2, 3];
2const doubled = nums.map(n => n * 2);
3console.log(doubled); // [2, 4, 6]

Use this when you want to transform the data, like changing values, adding something, or converting types.

πŸ” filter() – Keep only items that match a condition

This returns a new array with only the items that pass a test.

➀ Example:

1const scores = [45, 90, 60];
2const passed = scores.filter(score => score >= 60);
3console.log(passed); // [90, 60]

Use this when you want to remove some items based on a condition (like filtering students who passed).

🧠 reduce() – Turn all items into one single value

This method goes through the array and adds up or combines the values into one.

➀ Example:

1const arr = [1, 2, 3, 4];
2const total = arr.reduce((sum, current) => sum + current, 0);
3console.log(total); // 10
  • It starts from 0 (the second argument), and keeps adding each number.
  • Great for calculating totals, averages, or combining strings.

🧠 reduceRight() – Same as reduce, but starts from the end

This works just like reduce(), but it starts from the last item and moves backward.

➀ Example:

1const arr = [1, 2, 3];
2const result = arr.reduceRight((a, b) => a - b);
3console.log(result); // 0 β†’ ((3 - 2) - 1)

Mostly used when order matters, like reversing logic or working with strings from end to start.

πŸ” 3. Searching & Finding in Arrays

Sometimes you need to look for something inside an array β€” like a value, an object, or its position. JavaScript gives us built-in methods to help with this.

❓ find() and findLast() – Get the first or last matching item

These methods return the first (or last) element that matches a condition. If nothing matches, it returns undefined.

➀ Example:

1const users = [{ id: 1 }, { id: 2 }];
2const found = users.find(u => u.id === 2);
3console.log(found); // { id: 2 }

➀ Example with findLast():

1const nums = [1, 2, 3, 2];
2const last = nums.findLast(n => n === 2);
3console.log(last); // 2 (the last one)

βœ… Use these when you need the actual item, not just its position.

πŸ”’ findIndex() and findLastIndex() – Get the position of the first/last match

These methods return the index of the first or last item that matches a condition. If nothing matches, it returns -1.

➀ Example:

1const numbers = [5, 10, 15];
2const index = numbers.findIndex(n => n > 10);
3console.log(index); // 2

➀ Example with findLastIndex():

1const nums = [1, 2, 3, 2];
2const lastIndex = nums.findLastIndex(n => n === 2);
3console.log(lastIndex); // 3

βœ… Use these when you need to know the position (index) of something in the array.

includes() – Check if a value exists

Checks if an array contains a specific value.

➀ Example

1const letters = ['a', 'b', 'c'];
2console.log(letters.includes('b')); // true
3console.log(letters.includes('z')); // false

βœ… Great for yes/no checks β€” very easy to read and use.

πŸ”’ indexOf() and lastIndexOf() – Find the position of a value

Returns the index of the first or last time a value appears in the array.

➀ Example:

1const letters = ['a', 'b', 'a'];
2console.log(letters.indexOf('a')); // 0  (first one)
3console.log(letters.lastIndexOf('a')); // 2  (last one)

If the value is not found, both return -1.

βœ… Use when you want to know where a value appears in the array.

βž• 4. Adding & Removing Items in Arrays

JavaScript arrays have built-in methods that make it easy to add, remove, or copy elements. Let’s break them down with real-world examples:

push() and pop() – Add/Remove at the end

  • push() adds an item to the end of the array.
  • pop() removes the last item from the array.

➀ Example:

1let arr = [1];
2arr.push(2); 
3console.log(arr); // [1, 2]
4
5arr.pop(); 
6console.log(arr); // [1]

Use this when you work with stacks or when you need to add/remove at the end.

unshift() and shift() – Add/Remove at the start

  • unshift() adds an item at the beginning.
  • shift() removes the first item.

➀ Example:

1let arr = [2];
2arr.unshift(1);
3console.log(arr); // [1, 2]
4
5arr.shift();
6console.log(arr); // [2]
7

Use this when you need to insert or remove items at the front of the list.

βœ‚οΈ splice() – Add, remove, or replace items anywhere

This method is very flexible. It can:

  • Remove items
  • Add new items
  • Replace existing items

➀ Syntax:

1array.splice(startIndex, deleteCount, item1, item2, ...)

➀ Example – Replace 1 item at index 1:

1const arr = ['a', 'b', 'c'];
2arr.splice(1, 1, 'x');
3console.log(arr); // ['a', 'x', 'c']

➀ Example – Remove 2 items from index 0:

1const fruits = ['apple', 'banana', 'cherry'];
2fruits.splice(0, 2);
3console.log(fruits); // ['cherry']

➀ Example – Insert without removing:

1const numbers = [1, 3];
2numbers.splice(1, 0, 2); 
3console.log(numbers); // [1, 2, 3]

splice() changes the original array, so use it carefully.

✨ slice() – Copy part of an array

This method returns a shallow copy of a portion of the array. It does not change the original array.

➀ Syntax:

1array.slice(startIndex, endIndex) // endIndex is not included

➀ Example:

1const letters = ['a', 'b', 'c', 'd'];
2const part = letters.slice(1, 3);
3console.log(part); // ['b', 'c']
4console.log(letters); // ['a', 'b', 'c', 'd'] – original unchanged

slice() is great when you want to copy or extract a part of an array safely.

5. Flattening & Combining Arrays in JavaScript

Sometimes you want to merge arrays together or flatten nested arrays into a single list. JavaScript offers powerful methods to do this easily.

πŸ” concat() – Combine multiple arrays

This method merges two or more arrays into one new array.
The original arrays are not changed.

➀ Example:

1const a = [1, 2];
2const b = [3, 4];
3const result = a.concat(b);
4console.log(result); // [1, 2, 3, 4]

You can also combine more than two:

1const result = [1].concat([2], [3, 4], [5]);
2console.log(result); // [1, 2, 3, 4, 5]

Use concat() when you want to merge arrays safely without modifying the originals.

flat() – Flatten nested arrays

This method removes nesting inside arrays and makes a flat version.

➀ Example :

1const nested = [1, [2, 3]];
2console.log(nested.flat()); // [1, 2, 3]

➀ Example – Deeper levels:

1const deeplyNested = [1, [2, [3, [4]]]];
2console.log(deeplyNested.flat(2)); // [1, 2, 3, [4]]

Use flat(depth) to control how deep it flattens:

  • flat(1) (default) β†’ one level deep
  • flat(2) β†’ two levels deep
  • flat(Infinity) β†’ fully flatten everything

Great for simplifying arrays from APIs or nested structures.

flatMap() – Map + Flat in one step

This combines the power of map() and flat() together.

  • First: it runs a mapping function on each element.
  • Then: it flattens the result by one level.

➀ Example:

1const words = ['x y', 'z'];
2const result = words.flatMap(word => word.split(' '));
3console.log(result); // ['x', 'y', 'z']

Use this when you're transforming and flattening at the same time especially helpful when working with strings or objects.

πŸ§ͺ 6. Testing Elements in Arrays

JavaScript arrays include helpful methods to test if elements match a condition. These don’t change the array they simply return true or false based on your logic.

every() – Do all items pass the test?

Returns true only if every item in the array satisfies the given condition.

➀ Example:

1const numbers = [2, 4, 6];
2const allEven = numbers.every(n => n % 2 === 0);
3console.log(allEven); // true

If even one item fails the test, it returns false:

1[2, 3, 4].every(n => n % 2 === 0); // false

Use when you want to make sure all elements follow a rule.

❓ some() – Do any items pass the test?

Returns true if at least one item matches the condition.

➀ Example:

1const numbers = [1, 3, 4];
2const hasEven = numbers.some(n => n % 2 === 0);
3console.log(hasEven); // true

If none of the elements match, it returns false:

1[1, 3, 5].some(n => n % 2 === 0); // false

Use when you're looking for even one match fast and efficient.

7. Sorting & Reversing Arrays

Sometimes, you’ll need to organize your data either by sorting it or simply reversing the order. JavaScript offers simple and powerful methods to do both.

sort() – Sort elements in place

By default, sort() arranges elements as strings in lexicographic (dictionary) order, not numerically!

➀ Default behavior (lexicographic):

1const nums = [3, 1, 2];
2nums.sort();
3console.log(nums); // [1, 2, 3] βœ… looks correct here

But with bigger numbers:

1const bigNums = [10, 2, 30];
2bigNums.sort();
3console.log(bigNums); // [10, 2, 30] ❌ incorrect order

Sorting numbers correctly:

Use a compare function:

1bigNums.sort((a, b) => a - b);
2console.log(bigNums); // [2, 10, 30]
  • a - b: Sorts in ascending order.
  • b - a: Sorts in descending order.

Sorting strings alphabetically:

1const names = ['Zoe', 'Anna', 'Mike'];
2names.sort(); // ['Anna', 'Mike', 'Zoe']

Sorting strings case-insensitively:

1const mixedCase = ['apple', 'Banana', 'cherry'];
2mixedCase.sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()));

Tip: Always use a compare function for accurate control over how things are sorted.

reverse() – Flip the order

This method reverses the array in-place, changing the original array.

➀ Example:

1const arr = [1, 2, 3];
2arr.reverse();
3console.log(arr); // [3, 2, 1]

Simple and useful when you want to go from last to first.

8. Converting Arrays to Strings

Sometimes, you need to turn an array into a string whether for display, storage, or processing. JavaScript provides simple methods to do this quickly.

join() – Join all elements into a string

This method combines all elements of an array into a single string, separated by the string you provide.

  • If you don’t specify a separator, it uses a comma , by default.

➀ Example:

1const letters = ['a', 'b', 'c'];
2const joined = letters.join('-');
3console.log(joined); // "a-b-c"

You can also join with spaces, no space, or any custom separator:

1letters.join(' '); // "a b c"
2letters.join('');  // "abc"

toString() – Convert array to string (comma-separated)

This method converts an array to a comma-separated string of its elements.

➀ Example:

1const numbers = [1, 2, 3];
2console.log(numbers.toString()); // "1,2,3"

This is similar to join(',') but less flexible because you can't change the separator.

9. New Immutable Array Methods

JavaScript keeps evolving! Since ES2023, new immutable array methods were introduced. These methods do not modify the original array, but instead return a new updated array. This makes your code safer and easier to reason about.

toSorted() – Sort without changing the original

Sorts the array without mutating it.

➀ Example:

1const nums = [3, 1, 2];
2const sorted = nums.toSorted();
3console.log(sorted); // [1, 2, 3]
4console.log(nums);   // [3, 1, 2] β€” original stays unchanged

toReversed() – Reverse without changing the original

Reverses the array without mutating it.

➀ Example:

1const arr = [1, 2, 3];
2const reversed = arr.toReversed();
3console.log(reversed); // [3, 2, 1]
4console.log(arr);      // [1, 2, 3] β€” original stays unchanged

toSpliced() – Splice without changing the original

Works like splice() but returns a new array without modifying the original.

➀ Example:

1const arr = [1, 2, 3];
2const spliced = arr.toSpliced(1, 1); // remove 1 element at index 1
3console.log(spliced); // [1, 3]
4console.log(arr);     // [1, 2, 3] β€” original unchanged

You can also add elements:

1arr.toSpliced(1, 0, 4, 5); // inserts 4 and 5 at index 1

with() – Replace an element immutably at a specific index

Returns a new array where the element at the given index is replaced.

➀ Example:

1const letters = ['a', 'b', 'c'];
2const updated = letters.with(1, 'x');
3console.log(updated); // ['a', 'x', 'c']
4console.log(letters); // ['a', 'b', 'c'] β€” original unchanged

Final Thoughts

JavaScript arrays are extremely versatile, and with the evolution of modern JavaScript (ES6 to ES2025), developers have a vast toolbox to write cleaner, more efficient code.

Mastering these array methods is a huge step toward becoming a strong front-end or full-stack developer.

Newsletter

Subscribe to our newsletter and get our latest updates.

Share with your friends: