- -- operator
- -= operator
- ++ operator
- += operator
- Accessing and setting content
- Array length
- Arrays
- Between braces
- Booleans
- Braces
- Calling the function
- Class
- Code block
- Conditions
- Console
- Constructor
- Creating a p element
- Else
- Else if
- Equality operator
- Extends
- Filter
- For Loops
- Function
- Function name
- Greater than
- Head element
- If statement
- Less than
- Map
- Methods
- Numbers
- Overriding methods
- Parameters
- Reduce
- Removing an element
- Replace
- Sort
- Splice
- Strings
- Substring
- Title
- While Loops
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.
How to Use JavaScript Arrays
Creating Arrays in JavaScript
JavaScript arrays are defined using square brackets ([]
). You can create an empty array or an array with elements. Elements of an array go within the square brackets, separated by commas.
// Creating an empty array
let emptyArray = [];
// Creating an array with elements
let fruits = ['apple', 'banana', 'cherry'];
Accessing Elements in JavaScript Arrays
Array elements are accessible through their index. JavaScript arrays use zero-based indexing, where the first element is at index 0.
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:
fruits.push('date');
The pop()
method removes the last element from an array and returns it:
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:
fruits.unshift('kiwi');
The shift()
method removes the first element from an array and returns it:
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.
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.
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.
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.
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:
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.
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.
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.
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.
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.
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 }
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.
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.
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.
const numbers = [1, 2, 3, 4, 5, 6];
let evenNumbers = numbers.filter(number => number % 2 === 0);
console.log(evenNumbers); // Outputs: [2, 4, 6]
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: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: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 true or false accordingly: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: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: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.
let matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
console.log(matrix[0][2]); // Access 3
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.