Javascript Creating And Manipulating Arrays Complete Guide
Understanding the Core Concepts of JavaScript Creating and Manipulating Arrays
JavaScript Creating and Manipulating Arrays
Creating Arrays
Array Literal Notation:
- This is the most common method to create arrays.
-
let fruits = ['apple', 'banana', 'cherry'];
Array Constructor:
- This method is less commonly used but can be useful to create arrays of a predefined size.
-
let numbers = new Array(1, 2, 3, 4, 5);
- Note: If you pass a single numeric argument to the Array constructor, it will create an empty array with the length of that number, not an array with a single element.
-
let arrayWithLength = new Array(5); // Creates an array with 5 empty slots
Using Spread Operator:
- The spread operator (
...
) allows an iterable such as an array to be expanded in places where zero or more arguments or elements are expected. -
let arr1 = [1, 2, 3]; let arr2 = [...arr1, 4, 5]; // [1, 2, 3, 4, 5]
- The spread operator (
Accessing and Modifying Array Elements
Accessing Elements:
- You can access array elements using their index (starting from 0).
-
let fruit = fruits[0]; // 'apple'
Modifying Elements:
- You can modify elements by assigning a new value to a specific index.
-
fruits[1] = 'blueberry'; // ['apple', 'blueberry', 'cherry']
Manipulating Arrays
Adding Elements:
push()
: Adds elements to the end of the array and returns the new length.-
fruits.push('mango'); // ['apple', 'blueberry', 'cherry', 'mango']
-
unshift()
: Adds elements to the start of the array and returns the new length.-
fruits.unshift('banana'); // ['banana', 'apple', 'blueberry', 'cherry', 'mango']
-
- Spread Operator:
-
let newFruits = [...fruits, 'peach']; // ['banana', 'apple', 'blueberry', 'cherry', 'mango', 'peach']
-
Removing Elements:
pop()
: Removes and returns the last element of the array.-
let lastFruit = fruits.pop(); // ['banana', 'apple', 'blueberry', 'cherry']
-
shift()
: Removes and returns the first element of the array.-
let firstFruit = fruits.shift(); // ['apple', 'blueberry', 'cherry']
-
splice()
: Changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.-
fruits.splice(1, 1); // ['apple', 'cherry'] (removes 'blueberry')
- To add an element:
-
fruits.splice(1, 0, 'blueberry'); // ['apple', 'blueberry', 'cherry']
-
-
Concatenating Arrays:
concat()
: Joins two or more arrays and returns a new array.-
let newFruits = fruits.concat(['blueberry', 'mango']); // ['apple', 'cherry', 'blueberry', 'mango']
-
Sorting Arrays:
sort()
: Sorts the elements of an array in place and returns the sorted array.-
newFruits.sort(); // ['apple', 'blueberry', 'cherry', 'mango']
-
- To sort numbers:
-
let nums = [4, 2, 5, 1, 3]; nums.sort((a, b) => a - b); // [1, 2, 3, 4, 5]
-
Reversing Arrays:
reverse()
: Reverses the elements of an array in place and returns the reversed array.-
fruits.reverse(); // ['cherry', 'blueberry', 'apple']
-
Slicing Arrays:
slice()
: Returns a shallow copy of a portion of an array into a new array object selected from start to end.-
let slicedFruits = fruits.slice(0, 2); // ['cherry', 'blueberry']
-
Iterating Over Arrays:
for...of
Loop:-
for (let fruit of fruits) { console.log(fruit); }
-
forEach()
Method:-
fruits.forEach(fruit => console.log(fruit));
-
Filtering Arrays:
filter()
: Creates a new array with all elements that pass the test implemented by the provided function.-
let filteredFruits = fruits.filter(fruit => fruit.startsWith('b')); // ['blueberry']
-
Mapping Arrays:
map()
: Creates a new array populated with the results of calling a provided function on every element in the calling array.-
let upperFruits = fruits.map(fruit => fruit.toUpperCase()); // ['CHERRY', 'BLUEBERRY', 'APPLE']
-
Reducing Arrays:
reduce()
: Applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.-
let total = [1, 2, 3, 4, 5].reduce((acc, curr) => acc + curr, 0); // 15
-
Checking Elements:
includes()
: Checks if an array contains a certain value among its entries, returning true or false.-
let hasApple = fruits.includes('apple'); // true
-
some()
: Tests whether at least one element in the array passes the test implemented by the provided function.-
let hasBlueberry = fruits.some(fruit => fruit.includes('blueberry')); // true
-
every()
: Tests whether all elements in the array pass the test implemented by the provided function.-
let allStartWithB = fruits.every(fruit => fruit.startsWith('b')); // false
-
Important Information
Immutable vs Mutable:
- Methods like
concat()
,slice()
,map()
,filter()
,reduce()
, andforEach()
do not change the original array, they return a new one or a value. - Methods like
push()
,pop()
,shift()
,unshift()
,reverse()
, andsort()
change the original array.
- Methods like
Performance Considerations:
- Array operations can be costly in terms of performance, especially for very large arrays. Methods like
splice()
should be used with caution, as they can be computationally expensive due to the potential need to shift multiple elements.
- Array operations can be costly in terms of performance, especially for very large arrays. Methods like
Handling Empty Slots:
- Sparse arrays can have empty slots, which can cause unexpected behavior with certain methods. Be mindful of the length of the array and any empty slots when using array methods.
Typed Arrays:
- JavaScript also provides typed arrays (like
Int8Array
,Uint8Array
, etc.) for handling numeric data, especially in performance-critical applications like WebGL, Game engines, and audio/video processing.
- JavaScript also provides typed arrays (like
Online Code run
Step-by-Step Guide: How to Implement JavaScript Creating and Manipulating Arrays
Creating Arrays in JavaScript
Step 1: Understanding Arrays
An array in JavaScript is a special type of variable, which can hold more than one value at a time. Arrays can hold any type of values: strings, numbers, objects, even functions.
Step 2: Creating an Array Using Array Literal
This is the simplest way to create an array.
// Empty array
let emptyArray = [];
// Array of numbers
let numbersArray = [1, 2, 3, 4, 5];
// Array of strings
let fruitsArray = ['Apple', 'Banana', 'Cherry'];
// Mixed type array
let mixedArray = ['Hello', 123, true];
Step 3: Creating an Array Using the Array Constructor
You can also create arrays using the Array constructor.
// Empty array
let emptyArray = new Array();
// Array of numbers
let numbersArray = new Array(1, 2, 3, 4, 5);
// Array of strings
let fruitsArray = new Array('Apple', 'Banana', 'Cherry');
Note: The Array constructor can be tricky. If you pass a single numerical value to the Array constructor, it creates an array with that length, not an array with that number as the only element.
let wrongArray = new Array(10); // This creates an array with 10 empty slots, not an array with one element 10.
Accessing Array Elements
Step 1: Indexing
JavaScript arrays are zero-indexed, meaning the first element is at index 0, the second is at index 1, and so on.
let fruits = ['Apple', 'Banana', 'Cherry'];
console.log(fruits[0]); // Output: Apple
console.log(fruits[1]); // Output: Banana
console.log(fruits[2]); // Output: Cherry
Step 2: Modifying Array Elements
You can change the value of an array element by referencing its index.
let fruits = ['Apple', 'Banana', 'Cherry'];
fruits[1] = 'Blueberry';
console.log(fruits); // Output: ['Apple', 'Blueberry', 'Cherry']
Array Length
Step 1: Getting the Length of an Array
You can determine how many elements are in an array using the length
property.
let fruits = ['Apple', 'Banana', 'Cherry'];
console.log(fruits.length); // Output: 3
Step 2: Setting the Length of an Array
You can also set the length of an array. If you set the length to a value smaller than the current length, the array will be truncated.
let fruits = ['Apple', 'Banana', 'Cherry'];
fruits.length = 2;
console.log(fruits); // Output: ['Apple', 'Banana']
Adding and Removing Elements
Step 1: Adding Elements to the End of an Array
You can use the push()
method to add elements to the end of an array.
let fruits = ['Apple', 'Banana'];
fruits.push('Cherry');
console.log(fruits); // Output: ['Apple', 'Banana', 'Cherry']
Step 2: Adding Elements to the Beginning of an Array
To add one or more elements to the beginning of an array, use the unshift()
method.
let fruits = ['Banana', 'Cherry'];
fruits.unshift('Apple');
console.log(fruits); // Output: ['Apple', 'Banana', 'Cherry']
Step 3: Removing Elements from the End of an Array
The pop()
method removes the last element from an array.
let fruits = ['Apple', 'Banana', 'Cherry'];
let removedFruit = fruits.pop();
console.log(fruits); // Output: ['Apple', 'Banana']
console.log(removedFruit); // Output: Cherry
Step 4: Removing Elements from the Beginning of an Array
The shift()
method removes the first element from an array.
let fruits = ['Apple', 'Banana', 'Cherry'];
let removedFruit = fruits.shift();
console.log(fruits); // Output: ['Banana', 'Cherry']
console.log(removedFruit); // Output: Apple
Combining and Splitting Arrays
Step 1: Combining Arrays
You can use the concat()
method to combine arrays.
let fruits = ['Apple', 'Banana'];
let vegetables = ['Carrot', 'Broccoli'];
let food = fruits.concat(vegetables);
console.log(food); // Output: ['Apple', 'Banana', 'Carrot', 'Broccoli']
Step 2: Splitting Arrays
To split an array into smaller arrays, use the slice()
method.
let fruits = ['Apple', 'Banana', 'Cherry', 'Date'];
let slicedFruits = fruits.slice(1, 3);
console.log(slicedFruits); // Output: ['Banana', 'Cherry']
Note: The slice()
method does not modify the original array; it returns a new array.
Looping Through Arrays
Step 1: Using for Loop
let fruits = ['Apple', 'Banana', 'Cherry'];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
// Output:
// Apple
// Banana
// Cherry
Step 2: Using for...of Loop (ES6+)
let fruits = ['Apple', 'Banana', 'Cherry'];
for (let fruit of fruits) {
console.log(fruit);
}
// Output:
// Apple
// Banana
// Cherry
Step 3: Using Array forEach Method
let fruits = ['Apple', 'Banana', 'Cherry'];
fruits.forEach(function(fruit) {
console.log(fruit);
});
// Output:
// Apple
// Banana
// Cherry
Searching and Sorting Arrays
Step 1: Finding an Element
To find an element in an array, you can use the indexOf()
and lastIndexOf()
methods.
let fruits = ['Apple', 'Banana', 'Cherry', 'Banana'];
// Find the index of 'Banana'
let firstIndex = fruits.indexOf('Banana');
console.log(firstIndex); // Output: 1
// Find the last occurrence of 'Banana'
let lastIndex = fruits.lastIndexOf('Banana');
console.log(lastIndex); // Output: 3
Step 2: Sorting Arrays
To sort an array, use the sort()
method.
let fruits = ['Cherry', 'Apple', 'Banana'];
fruits.sort();
console.log(fruits); // Output: ['Apple', 'Banana', 'Cherry']
Note: By default, the sort()
method sorts the elements as strings. For numerical sorting, provide a comparison function.
let numbers = [10, 5, 30, 20];
numbers.sort(function(a, b) { return a - b; });
console.log(numbers); // Output: [5, 10, 20, 30]
Step 3: Reversing Arrays
To reverse the elements of an array, use the reverse()
method.
let fruits = ['Apple', 'Banana', 'Cherry'];
fruits.reverse();
console.log(fruits); // Output: ['Cherry', 'Banana', 'Apple']
Removing and Inserting Elements at Specific Positions
Step 1: Splicing Elements
The splice()
method can be used to add or remove elements at specific positions in an array.
let fruits = ['Apple', 'Banana', 'Cherry'];
// Remove 1 element starting from index 1
fruits.splice(1, 1);
console.log(fruits); // Output: ['Apple', 'Cherry']
// Add 'Berries' and 'Grapes' at index 1
fruits.splice(1, 0, 'Berries', 'Grapes');
console.log(fruits); // Output: ['Apple', 'Berries', 'Grapes', 'Cherry']
// Replace 2 elements starting from index 1 with 'Orange'
fruits.splice(1, 2, 'Orange');
console.log(fruits); // Output: ['Apple', 'Orange', 'Cherry']
Step 2: Slicing Elements
The slice()
method extracts a section of an array and returns it as a new array, without modifying the original array.
let fruits = ['Apple', 'Banana', 'Cherry', 'Date'];
let slicedFruits = fruits.slice(1, 3);
console.log(slicedFruits); // Output: ['Banana', 'Cherry']
console.log(fruits); // Output: ['Apple', 'Banana', 'Cherry', 'Date']
Summary
This guide covered the basics of creating and manipulating arrays in JavaScript, including creating arrays, accessing elements, adding and removing elements, combining and splitting arrays, looping through arrays, searching and sorting arrays, and more. With this foundation, you should feel confident to work with arrays in your JavaScript projects.
Top 10 Interview Questions & Answers on JavaScript Creating and Manipulating Arrays
1. How do you create an array in JavaScript?
Answer: In JavaScript, you can create an array using array literal syntax or the Array
constructor.
- Array Literal:
let myArray = [1, 2, 3, 4];
- Array Constructor:
let myArray = new Array(1, 2, 3, 4);
The array literal is the most commonly used method.
2. What is the difference between push()
and unshift()
methods in JavaScript arrays?
Answer: Both methods add elements to an array, but they do so at different positions.
push()
: Adds one or more elements to the end of an array and returns the new length of the array.let fruits = ['banana', 'apple']; fruits.push('orange', 'grape'); // fruits is ['banana', 'apple', 'orange', 'grape']
unshift()
: Adds one or more elements to the beginning of an array and returns the new length of the array.let fruits = ['banana', 'apple']; fruits.unshift('orange', 'grape'); // fruits is ['orange', 'grape', 'banana', 'apple']
3. How can you remove the last element from an array and return it?
Answer: Use the pop()
method. It removes and returns the last element of the array.
let fruits = ['banana', 'apple', 'orange'];
let lastFruit = fruits.pop(); // fruits is ['banana', 'apple'], lastFruit is 'orange'
4. How do you remove the first element from an array and return it?
Answer: Use the shift()
method. It removes the first element from an array and returns the value of the removed element.
let fruits = ['banana', 'apple', 'orange'];
let firstFruit = fruits.shift(); // fruits is ['apple', 'orange'], firstFruit is 'banana'
5. How can you find the index of a specific element in an array?
Answer: Use the indexOf()
method. It returns the index of the first occurrence of the specified element, or -1
if it isn't present.
let fruits = ['banana', 'apple', 'orange'];
let appleIndex = fruits.indexOf('apple'); // appleIndex is 1
let pineappleIndex = fruits.indexOf('pineapple'); // pineappleIndex is -1
6. How do you slice a portion of an array without modifying the original array?
Answer: Use the slice()
method. This method returns a new array containing a shallow copy of a portion of the original array.
let fruits = ['banana', 'apple', 'orange', 'pear', 'peach'];
let slicedFruits = fruits.slice(1, 4); // slicedFruits is ['apple', 'orange', 'pear']
7. How do you add or remove elements from a specific position in an array?
Answer: Use the splice()
method. splice()
can add or remove elements at any position in the array. It modifies the original array and returns the removed elements.
Adding elements:
let fruits = ['banana', 'orange']; fruits.splice(1, 0, 'apple', 'pear'); // fruits is ['banana', 'apple', 'pear', 'orange']
Removing elements:
let fruits = ['banana', 'apple', 'orange', 'pear']; fruits.splice(1, 2); // fruits is ['banana', 'pear']
8. How do you convert a string into an array in JavaScript?
Answer: Use the split()
method on a string. This method splits the string into an array of substrings.
let fruitString = 'banana,apple,orange';
let fruitsArray = fruitString.split(','); // fruitsArray is ['banana', 'apple', 'orange']
9. How can you sort an array of numbers in JavaScript?
Answer: Use the sort()
method. By default, sort()
sorts elements as strings. For numbers, provide a comparison function.
let numbers = [4, 2, 5, 1, 3];
numbers.sort((a, b) => a - b); // numbers is [1, 2, 3, 4, 5]
10. How do you reverse the elements of an array in JavaScript?
Answer: Use the reverse()
method. This method reverses the elements of the array in place and returns the reversed array.
Login to post a comment.