JAVASCRIPT
JavaScript Array: Create, Filter, Sort, and Use Arrays in JS
In JavaScript, an array is a data structure that allows you to store multiple values in a single variable. Arrays in JavaScript can hold any data type, such as numbers, strings, or even other arrays and objects.
Quick Answer: What is a JavaScript Array?
A JavaScript array is a special variable that can hold more than one value at a time. Arrays are created using square brackets [], and the values inside are separated by commas. You can access elements by their index number, starting from 0.
Learn JavaScript on Mimo
How to Create and Use a JS Array:
JSX
// 1. Create an array of strings
const fruits = ['apple', 'banana', 'cherry'];
// 2. Access the first element (at index 0)
console.log(fruits[0]); // Output: 'apple'
// 3. Add a new element to the end
fruits.push('date');
console.log(fruits); // Output: ['apple', 'banana', 'cherry', 'date']
// 4. Find the number of elements in the array
console.log(fruits.length); // Output: 4
Arrays are one of the most fundamental and commonly used data structures in JavaScript for managing collections of data.
How to Use JavaScript Arrays
Creating Arrays in JavaScript
JavaScript arrays are defined using square brackets ([]). You can use the syntax to create an empty array or an array with elements. Elements of an array go within the square brackets, separated by commas.
JSX
// Creating an empty array
let emptyArray = [];
// Creating an array with elements
let fruits = ['apple', 'banana', 'cherry'];
You can initialize an empty array or predefine values at creation.
Accessing Elements in JavaScript Arrays
Array elements are accessible through their array index. JavaScript arrays use zero-based indexing, where the first element is at index 0.
JSX
let firstFruit = fruits[0]; // Accesses the first item ('apple')
let lastFruit = fruits[fruits.length - 1]; // Accesses the last item ('cherry')
Adding to an Array in JavaScript
In JavaScript, to add to an array, you can choose between several array methods. However, adding to an array works particularly well with the push() or unshift() method.
The push() method adds an element to the end of an array and modifies the original arr:
JSX
fruits.push('date');
The pop() method removes the last element from an array and returns it:
JSX
let lastItem = fruits.pop(); // 'date'
Removing From an Array in JavaScript
Like adding to an array, you can use similar array methods to remove elements from an array.
The unshift() method adds an element to the beginning of an array:
JSX
fruits.unshift('kiwi');
The shift() method removes the first element from an array and returns it:
JSX
let firstItem = fruits.shift(); // 'kiwi'
When to Use JavaScript Arrays
JavaScript arrays are necessary when you need to store, keep track of, or work with collections of data.
Handling Collections of Data
Arrays are ideal for storing collections of elements you need to access or manipulate.
JSX
let userDetails = [
{ name: 'John Doe', email: 'john@example.com' },
{ name: 'Jane Smith', email: 'jane@example.com' }
];
userDetails.forEach(user => {
console.log(`${user.name}: ${user.email}`);
});
Iterating Over Data
Arrays are convenient for iterating over collections of items, making them ideal for loops and other bulk operations.
JSX
let colors = ['red', 'green', 'blue'];
colors.forEach(function(color) {
console.log(color);
});
Dynamic Data Handling
Unlike in some other programming languages, JavaScript arrays can grow and shrink. With this capability, arrays are perfect for scenarios with dynamic data.
JSX
let apiData = [];
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => {
apiData = data;
console.log('Data loaded:', apiData);
});
Examples of JavaScript Arrays
Arrays are a common component of any JavaScript application. Here are some typical examples of how apps might use arrays:
Managing a User's Shopping Cart
An e-commerce application might use arrays to manage the items in a shopping cart.
JSX
let shoppingCart = ['milk', 'bread', 'eggs'];
shoppingCart.push('butter'); // Add an item
shoppingCart.splice(1, 1); // Remove 'bread'
console.log(shoppingCart); // ['milk', 'eggs', 'butter']
Registration Forms
Arrays are also perfect for collecting and storing data, like from registration forms:
JSX
let surveyResponses = [];
document.getElementById('submit').addEventListener('click', function() {
let response = document.getElementById('surveyInput').value;
surveyResponses.push(response);
});
Product Pages
Arrays often help display lists of data on web pages. For example, a furniture company's website might showcase its latest products using an array to dynamically generate HTML content.
JSX
let products = ['Table', 'Chair', 'Lamp'];
products.forEach(product => {
document.body.innerHTML += `<p>${product}</p>`;
});
Learn More About JavaScript Arrays
JavaScript Array Length
The array length property represents the number of elements in an array. The length of an array in JavaScript often appears in the condition of a for loop to iterate over an array.
JSX
let products = ['Table', 'Chair', 'Lamp'];
for (let i = 0; i < products.length; i++) {
console.log(products[i]);
}
Array + Array in JavaScript
In JavaScript, combining arrays is a common operation. However, using the + operator for combining two arrays converts them into strings and combines those strings instead.
JSX
let array1 = [1, 2, 3];
let array2 = [4, 5, 6];
let combination = array1 + array2;
console.log(combination); // Outputs: "1,2,34,5,6"
To combine two arrays into a single array, you can use the concat() method. concat() returns the combined array without modifying the original arrays.
JSX
let array1 = [1, 2, 3];
let array2 = [4, 5, 6];
let combination = array1.concat(array2);
console.log(combination); // Outputs: [1, 2, 3, 4, 5, 6]
JavaScript Array Find
The find() method in JavaScript arrays searches for an element in an array that satisfies a provided testing function. find() is useful when you need to get an object from an array that meets certain criteria. It returns the first matching element or undefined if none of the elements match.
JSX
const products = [
{ id: 1, name: 'Laptop', price: 1200 },
{ id: 2, name: 'Phone', price: 700 },
{ id: 3, name: 'Tablet', price: 500 }
];
const expensiveProduct = products.find(product => product.price > 1000);
console.log(expensiveProduct); // Outputs: { id: 1, name: 'Laptop', price: 1200 }
The indexOf() method helps locate the position of an element in an array.
JSX
let fruits = ['apple', 'banana', 'cherry'];
console.log(fruits.indexOf('banana')); // Output: 1 (index position of 'banana')
JavaScript Array Sort
The sort() method in JavaScript organizes the elements of an array in place and returns the array. sort() is ideal whenever you need to sort an array in a particular order.
However, the sort() method defaults to sorting elements as strings, which can lead to unexpected results when you sort numbers.
JSX
let numbers = [10, 2, 15, 1];
numbers.sort();
console.log(numbers); // Outputs: [1, 10, 15, 2] (sorted as strings)
In JavaScript, to sort an array numerically, you need to add a compare function to the sort() method. With a compare function, sort() sorts based on the return value of the compare function.
JSX
numbers.sort((a, b) => a - b);
console.log(numbers); // Outputs: [1, 2, 10, 15] (sorted numerically)
JavaScript Array Filter
The filter() method in JavaScript creates a new array with all elements that pass the test implemented by the provided function. filter() useful when you need to get a subset of an array based on certain criteria. It returns the an array of matching elements or an empty array if none of the elements match.
JSX
const numbers = [1, 2, 3, 4, 5, 6];
let evenNumbers = numbers.filter(number => number % 2 === 0);
console.log(evenNumbers); // Outputs: [2, 4, 6]
The filter() method requires a callback function as its parameter, which determines the condition each array element must satisfy."
JSX
const numbers = [1, 2, 3, 4, 5, 6];
let evenNumbers = numbers.filter((number) => number % 2 === 0); // Callback function as a parameter
Advanced Array Methods
JavaScript offers a range of array methods that allow for basic and advanced manipulations. Here’s an overview of some additional array methods:
-
concat()merges two or more arrays into one, demonstrating basic array combination:JSX
let array1 = ['a', 'b', 'c']; let array2 = ['d', 'e', 'f']; let combinedArray = array1.concat(array2); console.log(combinedArray); // Output: ['a', 'b', 'c', 'd', 'e', 'f'] -
slice()extracts a section of an array and returns a new array without modifying the original:JSX
let items = ['item1', 'item2', 'item3', 'item4']; let selectedItems = items.slice(1, 3); console.log(selectedItems); // Output: ['item2', 'item3'] -
includes()checks if an array includes a certain element, returning a boolean true or false accordingly:JSX
let fruits = ['apple', 'banana', 'mango']; let hasBanana = fruits.includes('banana'); console.log(hasBanana); // Output: true -
map()creates a new array populated with the results of calling a provided function on every element in the calling array:JSX
let numbers = [1, 2, 3, 4]; let squares = numbers.map(num => num * num); console.log(squares); // Output: [1, 4, 9, 16] -
reduce()executes a reducer function on each element of the array, resulting in a single output value, often used for summing or constructing objects:JSX
let sum = numbers.reduce((acc, curr) => acc + curr, 0); console.log(sum); // Output: 10
Multi-dimensional Arrays
JavaScript supports multi-dimensional arrays (arrays of arrays), useful for complex data structures like matrices or tables.
JSX
let matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
console.log(matrix[0][2]); // Access 3
Join 35M+ people learning for free on Mimo
4.8 out of 5 across 1M+ reviews
Check us out on Apple AppStore, Google Play Store, and Trustpilot