JavaScript Array Methods
JavaScript arrays are a fundamental part of web development, providing powerful ways to store, manipulate, and process data. Understanding how to work with arrays effectively can significantly improve the performance and readability of your code. In this guide, we’ll explore essential JavaScript array methods, from basic operations like adding and removing elements to more advanced techniques for searching, filtering, and transforming data. Whether you’re building dynamic web applications or handling large datasets, mastering these array methods will streamline your development workflow.
Table of Contents
- Array Methods
sort()reverse()
push()andpop()shift()andunshift()concat()join()
Searching and Indexing Methods
indexOf()lastIndexOf()includes()find()andfindIndex()
forEach()map()filter()some()andevery()
slice()splice()fill()
toString()Array.isArray()
sorting and reversing methods
sort()andreverse()
1. sort() Method
The sort() method is used to arrange the elements of an array in
a specific order (default is ascending). It works by converting
elements to strings and then comparing their UTF-16 code values,
which may not always provide expected results for numbers.
Example 1: Sorting Strings
const fruits = ['apple', 'orange', 'banana', 'grape'];
fruits.sort();
console.log(fruits); // Output: ['apple', 'banana', 'grape', 'orange']
Example 2: Sorting Numbers (Without Callback)
const numbers = [10, 3, 5, 25, 1];
numbers.sort();
console.log(numbers); // Output: [1, 10, 25, 3, 5]
This may seem incorrect, but the issue arises because sort()
compares numbers as strings.
To properly sort numbers, you must pass a compare function.
Example 3: Sorting Numbers (With Callback)
const numbers = [10, 3, 5, 25, 1];
numbers.sort((a, b) => a - b);
console.log(numbers); // Output: [1, 3, 5, 10, 25]
-----------------------------------------------------------------------------
2. reverse() Method
The reverse() method reverses the elements in an array.
It modifies the array in place and returns the reversed array.
Example 1: Reversing an Array
const letters = ['a', 'b', 'c', 'd'];
letters.reverse();
console.log(letters); // Output: ['d', 'c', 'b', 'a']
Example 2: Combining sort() and reverse()
You can combine sort() and reverse() to first sort an array in ascending order
and then reverse it to get descending order.
const numbers = [10, 3, 5, 25, 1];
numbers.sort((a, b) => a - b).reverse();
console.log(numbers); // Output: [25, 10, 5, 3, 1]
Here, sort() arranges the numbers in ascending order,
and reverse() flips them into descending order.concat and join methods
concat()andjoin()
1. concat() Method - The concat() method is used to merge two or more arrays.
const array1 = ['a', 'b'];
const array2 = ['c', 'd'];
const array3 = ['e', 'f'];
const result = array1.concat(array2, array3);
console.log(result); // Output: ['a', 'b', 'c', 'd', 'e', 'f']
console.log(array1); // Output: ['a', 'b'] (original array unchanged)
----------------------------------------------------------------------------
2. join() Method - The join() method is used to join all elements of an array
into a string, separated by a specified separator.
If no separator is specified, a comma is used by default.
Example 1: Joining an Array into a String (Comma Separator)
const fruits = ['apple', 'banana', 'cherry'];
const result = fruits.join();
console.log(result); / Output:'apple,banana,cherry' => a comma default behavior
Example 2: Joining an Array with a Custom Separator
const fruits = ['apple', 'banana', 'cherry'];
const result = fruits.join(' - ');
console.log(result); // Output: 'apple - banana - cherry'
Example 3: Joining Array without Separator
const letters = ['a', 'b', 'c'];
const result = letters.join('');
console.log(result); // Output: 'abc'find and findIndex methods
find()andfindIndex()
1. find() Method - The find() method returns the first element in an array
that satisfies a condition. If no element satisfies the condition,
it returns undefined.
const age= [10,12,28,18,36]
const b = age.find((item)=>{
return item > 18
})
document.write(b) // Output: 28
or
const age= [10,12,28,18,36]
const b = age.find(checkAdultAge);
document.write(b); // Output: 28
function checkAdultAge = (age){
return age > 18;
}
---------------------------------------------------------------------------
2. findIndex() Method - The findIndex() method returns the index of the
first element in an array that satisfies a condition.
If no element satisfies the condition, it returns -1.
var age= [10,12,28,18,36]
var b = age.findIndex((item)=>{
return item > 18
})
document.write(b) // Output: 2map and filter methods
map()andfilter()
1. The map() method creates a new array populated with the results of calling
a provided function on every element in the original array.
the returned array is always the same length as the original.
Example 1: Extracting data from an Array of Objects
const users = [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 },
{ name: 'Charlie', age: 35 }
];
const names = users.map(user => user.name);
document.write(names); // Output: ['Alice', 'Bob', 'Charlie']
or
const users = [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 },
{ name: 'Charlie', age: 35 },
];
const names = users.map((items)=>{
return items.name
})
document.write(names)
---------------------------------------------------------------------------
2. filter() Method - The filter() method creates a new array with all elements
that pass the test implemented by the provided function.
Only elements that return true in the callback function are included in a array.
const users = [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 },
{ name: 'Charlie', age: 35 }
];
const adults = users.filter(user => user.age >= 30);
console.log(adults);
// Output: [{ name: 'Bob', age: 30 }, { name: 'Charlie', age: 35 }]Differences Between map() and filter()
- Purpose:
map()transforms the elements and returns a new array with the same length as the original, whilefilter()returns a new array with fewer elements, containing only those that pass the provided test. - Return Values:
map()can change each element, whereasfilter()either includes or excludes elements based on the condition.
some and every methods
some()andevery()
some() returns true if at least one element satisfies the condition.
every() returns true only if all elements satisfy the condition.
Both methods return a boolean value (true or false),
depending on whether the condition is met
1. some()
var ages = [10,20,12,30,15];
var b = ages.some(checkUserAge)
function checkUserAge(userage) {
return userage < 18
}
document.write(b) // Output: true
--------------------------------------------------------------------------
2. every()
const users = [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 },
{ name: 'Charlie', age: 17 }
];
const allAdults = users.every(user => user.age >= 18);
console.log(allAdults); // Output: falseslice and splice methods
slice()andsplice()
1. The slice() method returns a copy of an array into a new array,
selected from start to end (end not included).
NOTE : It does not modify the original array.
Syntax: array.slice(start, end)
Example 1: Extracting a part of an Array
const fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry'];
const slicedFruits = fruits.slice(1, 4);
// from index 1 to 3 (not including index 4),
console.log(slicedFruits); // Output: ['banana', 'cherry', 'date']
console.log(fruits); // Output: ['apple', 'banana'...]
Example 2: Using slice() Without an End Index
const numbers = [1, 2, 3, 4, 5];
const slicedNumbers = numbers.slice(2);
console.log(slicedNumbers); // Output: [3, 4, 5]
---------------------------------------------------------------------------
2. splice() Method - The splice() method modifies the contents of an array
by removing, replacing, or adding elements at a specified index.
Unlike slice(), it can change the original array.
Syntax: array.splice(start, deleteCount, item1, item2, ...)
start: The index at which to start changing the array.
deleteCount: The number of elements to remove. If 0, no elements are removed.
item1, item2, ...: Optional elements to add at the start index.
Example 1: Removing Elements
const fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry'];
const removedFruits = fruits.splice(1, 2);
console.log(removedFruits); // Output: ['banana', 'cherry']
console.log(fruits); // Output: ['apple', 'date', 'elderberry']
Here, splice() removes two elements starting from index 1 (banana and cherry),
modifying the original array.
Example 2: Adding Elements
const animals = ['dog', 'cat', 'rabbit'];
animals.splice(1, 0, 'elephant', 'lion');
console.log(animals); // Output: ['dog', 'elephant', 'lion', 'cat', 'rabbit']
In this example,
splice(1, 0, 'elephant', 'lion') inserts the new elements starting at index 1
without removing any existing elements.
Example 3: Replacing Elements
const colors = ['red', 'green', 'blue'];
colors.splice(1, 1, 'yellow', 'orange');
console.log(colors); // Output: ['red', 'yellow', 'orange', 'blue']
Here, splice(1, 1, 'yellow', 'orange') removes one element at index 1 (green)
and replaces it with 'yellow' and 'orange'.toString and includes methods
toString()andincludes()
toString() returns a string.
includes() returns a boolean (true or false).
1. toString() Method - It converts an array into a comma-separated string.
Each element of the array is concatenated into a single string,
with commas inserted between elements. It does not modify the original array.
Syntax: array.toString()
Example 1: Converting an Array to a String
const fruits = ['apple', 'banana', 'cherry'];
const stringFruits = fruits.toString();
console.log(stringFruits); // Output: 'apple,banana,cherry'
console.log(fruits); // Output: ['apple', 'banana', 'cherry']
----------------------------------------------------------------------------
2. includes() Method - It determines whether an array contains a certain element.
It returns a boolean value—true if the element is found, and false otherwise.
This method is case-sensitive.
Syntax: array.includes(element, start)
element: The element to search for.
start (optional): The position in the array at which to begin the search.
Defaults to 0.
Example 1: Checking if an Array Contains a String
const fruits = ['apple', 'banana', 'cherry'];
const hasBanana = fruits.includes('banana');
console.log(hasBanana); // Output: true
Example 2: Using a Start Index in includes()
const numbers = [1, 2, 3, 4, 5];
const hasTwoAfterIndex2 = numbers.includes(2, 2);
console.log(hasTwoAfterIndex2); // Output: false
Here, includes() starts searching from index 2.
Since 2 appears before index 2, the method returns false.push , pop , shift , unshift methods
push(),pop(),shift(),unshift()
push() adds elements to the end of the array.
pop() removes the last element from the array.
shift() removes the first element from the array.
unshift() adds elements to the beginning of the array.
1. push() Method - It adds one or more elements to the end of an array
and returns the new length of the array. It modifies the original array.
Example: Adding Elements to the End of an Array
const fruits = ['apple', 'banana'];
const newLength = fruits.push('cherry', 'date');
console.log(fruits); // Output: ['apple', 'banana', 'cherry', 'date']
2. pop() Method - It removes the last element from an array
and returns that element. This method modifies the original array.
Example: Removing the Last Element from an Array
const fruits = ['apple', 'banana', 'cherry'];
const removedFruit = fruits.pop();
console.log(fruits); // Output: ['apple', 'banana']
console.log(removedFruit); // Output: 'cherry'
3. shift() Method - It removes the first element from an array and returns
that element. This method modifies the original array.
Example: Removing the First Element from an Array
const fruits = ['apple', 'banana', 'cherry'];
const removedFruit = fruits.shift();
console.log(fruits); // Output: ['banana', 'cherry']
4. unshift() Method - It adds one or more elements to the beginning of an array
and returns the new array. It modifies the original array.
Example: Adding Elements to the Beginning of an Array
const fruits = ['banana', 'cherry'];
const newLength = fruits.unshift('apple', 'date');
console.log(fruits); // Output: ['apple', 'date', 'banana', 'cherry']isarray , indexOf , lastIndexOf methods
isArray(),indexOf(),lastIndexOf()
Array.isArray() checks whether a value is an array.
indexOf() searches for the first occurrence of an element in an array.
lastIndexOf() searches for the last occurrence of an element in an array.
1. Array.isArray() Method - It checks whether a given value is an array.
It returns true if the value is an array, and false if it is not.
Example 1: Checking if a Value is an Array
const fruits = ['apple', 'banana', 'cherry'];
const notAnArray = 'hello';
console.log(Array.isArray(fruits)); // Output: true
console.log(Array.isArray(notAnArray)); // Output: false
2. indexOf() Method - It returns the first index at which a specified element
is found in the array, or -1 if the element is not found.
It performs a strict equality comparison (===).
Syntax: array.indexOf(element, start)
element: The element to search for.
start (optional): The index to start the search from. Defaults to 0.
Example 1: Finding the Index of an Element
const fruits = ['apple', 'banana', 'cherry', 'apple'];
const index = fruits.indexOf('apple');
console.log(index); // Output: 0
Example 2: Using a Start Index
const fruits = ['apple', 'banana', 'cherry', 'apple'];
const index = fruits.indexOf('apple', 1);
console.log(index); // Output: 3
Example 3: When the Element is Not Found
const fruits = ['apple', 'banana', 'cherry'];
const index = fruits.indexOf('date');
console.log(index); // Output: -1
3. lastIndexOf() Method -It starts searching from the end of the array and
returns the last index at which a specified element is found in the array,
or -1 if the element is not found. it also performs a strict equality
Syntax: array.lastIndexOf(element, start)
element: The element to search for.
start (optional): The index to start searching backwards from.
Example 1: Finding the Last Occurrence of an Element
const fruits = ['apple', 'banana', 'cherry', 'apple'];
const lastIndex = fruits.lastIndexOf('apple');
console.log(lastIndex); // Output: 3
In this example, lastIndexOf() returns 3,
the index of the last occurrence of 'apple' in the array.
Example 2: Using a Start Index
const fruits = ['apple', 'banana', 'cherry', 'apple'];
const lastIndex = fruits.lastIndexOf('apple', 2);
console.log(lastIndex); // Output: 0
Here, lastIndexOf('apple', 2) starts searching backward from index 2,
so it returns 0, the index of the first 'apple'.
Example 3: When the Element is Not Found
const fruits = ['apple', 'banana', 'cherry'];
const lastIndex = fruits.lastIndexOf('date');
console.log(lastIndex); // Output: -1forEach, some , every , fill methods
forEach(),some(),every(),fill()
forEach() iterates over each element of the array without returning a value.
some() checks if at least one element passes a test.
every() checks if all elements pass a test.
fill() modifies the array by filling it with a static value.
1. forEach() Method - It executes a provided function
once for each array element. It is used for iterating over an array
but does not return any value.
Syntax: array.forEach(callback(element, index, array), thisArg)
callback: A function to execute for each element.
element: The current element being processed.
index (optional): The index of the current element.
array (optional): The array that forEach() is called upon.
Example 1: Iterating Over an Array
const fruits = ['apple', 'banana', 'cherry'];
fruits.forEach((fruit, index) => {
console.log(`${index}: ${fruit}`);
});
// Output:
// 0: apple
// 1: banana
// 2: cherry
In this example,
It iterates over the fruits array and logs each fruit along with itsindex.
Example 2: Summing Values in an Array
const numbers = [1, 2, 3, 4, 5];
let sum = 0;
numbers.forEach(number => {
sum += number;
});
console.log(sum); // Output: 15
Here, forEach() is used to sum all the elements of the numbers array.
2. some() Method - tests whether at least one element in the array passes
the test implemented by the provided function.
It returns a boolean (true or false).
Example 1: Checking age is greater than 18 or not.
const age = [10,12,15,18,13,5]
const CheckAge = age.some(checkAdult)
function checkAdult(ages){
return age > = 18;
}
document.write(CheckAge); // Output : true
3. every() Method - It tests whether all elements in the array pass the test
implemented by the provided function.
It returns true if all elements pass the test,
and false if at least one element fails.
Example 1: Checking age is greater than 18 or not.
const age = [10,12,15,18,13,5]
const CheckAge = age.every(checkAdult)
function checkAdult(ages){
return age > = 18;
}
document.write(CheckAge); // Output : false
4. fill() Method - It changes all elements in an array to a static value,
from a start index to an end index (not included).
It modifies the original array.
Syntax: array.fill(value, start, end)
value: The value to fill the array with.
start (optional): The index to start filling (inclusive). Defaults to 0.
end (optional): The index to stop filling (exclusive).
Example 1: Filling an Array with a Value
const numbers = [1, 2, 3, 4, 5];
numbers.fill(0);
console.log(numbers); // Output: [0, 0, 0, 0, 0]
Example 2: Filling a Portion of an Array
const numbers = [1, 2, 3, 4, 5];
numbers.fill(9, 1, 4);
console.log(numbers); // Output: [1, 9, 9, 9, 5]2. String Methods
Get ΛK⚡HΛY’s stories in your inbox
Join Medium for free to get updates from this writer.
If you’re interested in diving deeper into JavaScript string methods, I recommend checking out this comprehensive guide on Medium: JavaScript String Methods. It provides detailed explanations and examples to help you master string manipulation in JavaScript. Happy learning!
3. Number Methods
toFixed(),toPrecision(),toString()parseInt()andparseFloat()Number.isInteger(),Number.isNaN()toExponential()andvalueOf()
4. Math Methods
Math.round(),Math.floor(),Math.ceil()Math.max(),Math.min()Math.random()Math.pow(),Math.sqrt(),Math.abs()
5. Date Methods
Date(),getDate(),setDate()getDay(),getMonth(),getFullYear()getTime(),getTimezoneOffset()toLocaleDateString(),toISOString()
Conclusion
In summary, mastering JavaScript array methods is vital for web developers aiming to create dynamic and efficient applications. From basic operations like push(), pop(), and shift(), to more advanced techniques such as map(), filter(), and reduce(), these methods provide powerful tools for data manipulation.
As you continue to develop your projects, leveraging these array methods will enhance your coding efficiency and help you manage data more effectively. Keep exploring and experimenting with them to elevate your web development skills.
Happy coding!








