Lesson 23 of 36 · 5 min
Arrays
Explore the world of JavaScript arrays: Learn how to create, manipulate, and work with collections of data using built-in methods and properties.
On this page
- Syntax :
- Array Properties :
- Array Methods :
- Adding and Removing Elements
- push() and pop()
- shift() and unshift()
- Combining and Extracting Arrays
- concat()
- slice()
- Iterating through Arrays
- forEach()
- Transforming Arrays
- map()
- filter()
- Searching and Finding Elements
- find()
- findIndex()
- Array Data Validation
- some() and every()
- Reducing Arrays
- reduce() and reduceRight()
- Sorting and Reversing
- sort()
- reverse()
- Checking for Element Existence
- includes() , indexOf() , and lastIndexOf()
- Conclusion
In JavaScript, there isn’t an “Arrays Object” per se; instead, arrays are a fundamental data structure used for storing collections of data. However, JavaScript provides an extensive set of built-in methods and properties for working with arrays efficiently.
Here’s a brief overview of how arrays work in JavaScript:
Syntax :
You can create an array by enclosing a list of values within square brackets [].
let fruits = ['apple', 'banana', 'cherry'];
Array Properties :
In JavaScript, arrays are versatile data structures used to store collections of items. While they are not objects in themselves, they have properties that provide useful information about the array’s characteristics and elements. Here are some essential array properties:
1. length Property:
- The
lengthproperty returns the number of elements in an array. - Example:
let colors = ["red", "green", "blue"];
let numberOfColors = colors.length; // 3
2. constructor Property:
- The
constructorproperty refers to the constructor function that created the array. - Example:
let numbers = [1, 2, 3];
console.log(numbers.constructor); // Output: [Function: Array]
3. prototype Property:
- The
prototypeproperty allows you to add properties and methods to all instances of an array, enhancing its behavior. - Example:
Array.prototype.sum = function() {
return this.reduce((total, current) => total + current, 0);
};
let myArray = [1, 2, 3, 4, 5];
let sum = myArray.sum(); // 15
4. Symbol.species Property:
- The
Symbol.speciesproperty is used for specifying the constructor function that is used to create derived array objects. - Example:
class MyArray extends Array {}
MyArray[Symbol.species] = Array;
let customArray = new MyArray(1, 2, 3);
console.log(customArray instanceof MyArray); // true
console.log(customArray instanceof Array); // true
These array properties are helpful for understanding and manipulating arrays in JavaScript, providing developers with valuable insights into the structure and characteristics of arrays. Understanding and using these properties can make working with arrays more efficient and powerful in your JavaScript code.
Array Methods :
Adding and Removing Elements
push() and pop()
The push() method allows you to add one or more elements to the end of an array. It returns the new length of the array.
fruits.push("orange");
// fruits is now ["apple", "banana", "cherry", "orange"]
Conversely, the pop() method removes the last element from an array and returns that element.
let removedFruit = fruits.pop();
// removedFruit is "orange", fruits is ["apple", "banana", "cherry"]
shift() and unshift()
shift() removes the first element from an array and returns it, shifting the remaining elements to lower indices.
let removedFruit = fruits.shift();
// removedFruit is "apple", fruits is ["banana", "cherry"]
On the other hand, unshift() adds one or more elements to the beginning of an array and returns the new length.
fruits.unshift("kiwi", "grape");
// fruits is now ["kiwi", "grape", "banana", "cherry"]
Combining and Extracting Arrays
concat()
The concat() method combines two or more arrays and returns a new array, leaving the original arrays unchanged.
let colors1 = ["red", "green"];
let colors2 = ["blue", "yellow"];
let combinedColors = colors1.concat(colors2);
// combinedColors is ["red", "green", "blue", "yellow"]
slice()
slice() extracts a portion of an array and returns a new array with the selected elements. It takes two arguments, the start index (inclusive) and the end index (exclusive).
let animals = ["lion", "tiger", "cheetah", "leopard"];
let bigCats = animals.slice(1, 3);
// bigCats is ["tiger", "cheetah"]
Iterating through Arrays
forEach()
The forEach() method executes a provided function once for each array element. It is useful for performing actions on each element without the need for a traditional for loop.
let numbers = [1, 2, 3];
numbers.forEach(function (number) {
console.log(number);
});
// Output: 1, 2, 3
Transforming Arrays
map()
map() creates a new array by applying a provided function to each element of the original array. It is particularly useful when you want to transform the elements of an array and create a new array of the same length.
let numbers = [1, 2, 3];
let squaredNumbers = numbers.map(function (number) {
return number * number;
});
// squaredNumbers is [1, 4, 9]
filter()
The filter() method creates a new array with all elements that pass a given test (provided by a function). It’s an excellent choice when you want to extract specific elements from an array.
let ages = [25, 18, 30, 15, 22];
let adults = ages.filter(function (age) {
return age >= 18;
});
// adults is [25, 18, 30, 22]
Searching and Finding Elements
find()
find() returns the first element in an array that satisfies a provided testing function. It’s handy when you need to find a single element based on a condition.
let fruits = ["apple", "banana", "cherry"];
let result = fruits.find(function (fruit) {
return fruit.length > 5;
});
// result is "banana"
findIndex()
Similar to find(), but findIndex() returns the index of the first element that satisfies a provided testing function.
let fruits = ["apple", "banana", "cherry"];
let index = fruits.findIndex(function (fruit) {
return fruit.length > 5;
});
// index is 1 (index of "banana")
Array Data Validation
some() and every()
some() checks if at least one element in an array satisfies a provided testing function. It returns true if at least one element passes the test; otherwise, it returns false.
let numbers = [1, 2, 3, 4, 5];
let hasEvenNumber = numbers.some(function (number) {
return number % 2 === 0;
});
// hasEvenNumber is true
every() checks if all elements in an array satisfy a provided testing function. It returns true if all elements pass the test; otherwise, it returns false.
let numbers = [1, 2, 3, 4, 5];
let allEvenNumbers = numbers.every(function (number) {
return number % 2 === 0;
});
// allEvenNumbers is false
Reducing Arrays
reduce() and reduceRight()
The reduce() method applies a function to an accumulator and each element in the array (from left to right) to reduce it to a single value.
let numbers = [1, 2, 3, 4, 5];
let sum = numbers.reduce(function (accumulator, current) {
return accumulator + current;
}, 0);
// sum is 15
reduceRight() is similar to reduce(), but it processes the array from right to left.
Sorting and Reversing
sort()
The sort() method sorts the elements of an array in place and returns the sorted array. By default, it sorts elements as strings based on their Unicode code points.
let fruits = ["banana", "cherry", "apple"];
fruits.sort();
// fruits is now ["apple", "banana", "cherry"]
To sort numeric values correctly, you can provide a compare function:
let
numbers = [3, 1, 2, 10];
numbers.sort(function (a, b) {
return a - b;
});
// numbers is now [1, 2, 3, 10]
reverse()
The reverse() method reverses the order of elements in an array in place.
let colors = ["red", "green", "blue"];
colors.reverse();
// colors is now ["blue", "green", "red"]
Checking for Element Existence
includes(), indexOf(), and lastIndexOf()
includes() checks if an array includes a certain element and returns true or false.
let fruits = ["apple", "banana", "cherry"];
let hasBanana = fruits.includes("banana");
// hasBanana is true
indexOf() returns the first index at which a specified element can be found in the array or -1 if it’s not present.
let fruits = ["apple", "banana", "cherry"];
let index = fruits.indexOf("cherry");
// index is 2
lastIndexOf() returns the last index at which a specified element can be found in the array or -1 if it’s not present.
let fruits = ["apple", "banana", "cherry", "apple"];
let lastIndex = fruits.lastIndexOf("apple");
// lastIndex is 3
Conclusion
JavaScript array methods are powerful tools for working with arrays. They simplify common tasks, provide efficient ways to process and transform data, and make your code more expressive and readable. By mastering these array methods, you’ll become a more proficient JavaScript developer, capable of handling complex data manipulation tasks with ease.
More from JavaScript Tutorial
- Lesson 25 · 2 minThe Math ObjectExplore the JavaScript Math object with examples. Learn how to perform mathematical operations and utilize constants in your JavaScript code…
- Lesson 26 · 8 minRegular Expressions and RegExp ObjectDiscover Regular Expressions (RegEx) and the RegExp Object in JavaScript. Learn to search, match, and manipulate text with powerful patterns and…
- Lesson 27 · 3 minDocument Object Model (DOM)Explore the significance of the Document Object Model (DOM) in web development. Learn how JavaScript interacts with the DOM for dynamic web pages.