Video version link: https://www.youtube.com/watch?v=3DE4-o23tPc
Continuing our series of building javaScript method from Scratch for beginners, in this blog we will be making these 2 methods :
Array.push()
Array.concat()
and to make these methods we are allowed to use method that we have already build ,so let’s start.
Same as previous post,
First i will be introducing the array method with their example input and output, then we will examine those methods, identifying which programming tools and tricks to used and in which order to arrange them. Along that process we will build pseudocode algorithm for required function and later on, i will show you flowchart version of that algorithm, the important tip that i can give to you all, to get most out of this blog, is to first try to build it by yourself then come to this blog.
- Array.push():
First is Array.push() method, The push method of array instances adds the specified elements to the end of an array and returns the new length of the array.
So, from looking at example input and output and definition of the method , we have to somehow calculate length of array and then return it. Well, remember we could use methods that we have already build, so we could use length method, actually property to find length of array.
Next, we have to add given element to the end of an array, but we can’t use push method so, how? Well, let’s go to basics, remember:
" JavaScript programming language supports dynamic arrays, which means that the array data structure can automatically adjust its size to accommodate new elements as they are added. This capability allows for flexible and efficient management of collections of data without needing to manually allocate and manage memory or resize the array."
Supporting dynamic arrays means that the array data structure can automatically adjust its size to accommodate new elements as they are added. This capability allows for flexible and efficient management of collections of data without needing to manually allocate and manage memory or resize the array.
Key Features of Dynamic Arrays:
-
Automatic Resizing:
- Dynamic arrays grow or shrink automatically as elements are added or removed. This is in contrast to static arrays, which have a fixed size that cannot be changed after they are created.
-
Efficient Memory Management:
- Dynamic arrays manage memory allocation and reallocation internally. When the array reaches its capacity, it typically allocates a larger block of memory, copies the existing elements to the new block, and then continues adding new elements.
-
Ease of Use:
- Users can add, remove, or access elements without worrying about the underlying memory management. This makes dynamic arrays much easier to use compared to static arrays, especially when the number of elements can vary.
Examples in Various Languages:
JavaScript
JavaScript arrays are inherently dynamic:
let arr = [1, 2, 3];
arr.push(4); // Adds an element to the end of the array
console.log(arr); // Output: [1, 2, 3, 4]
Python
Python lists are dynamic:
arr = [1, 2, 3]
arr.append(4) # Adds an element to the end of the list
print(arr) # Output: [1, 2, 3, 4]
Java
Java's ArrayList is a dynamic array:
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> arr = new ArrayList<>();
arr.add(1);
arr.add(2);
arr.add(3);
arr.add(4); // Adds an element to the end of the ArrayList
System.out.println(arr); // Output: [1, 2, 3, 4]
}
}
C++
C++'s std::vector is a dynamic array:
#include <vector>
#include <iostream>
int main() {
std::vector<int> arr = {1, 2, 3};
arr.push_back(4); // Adds an element to the end of the vector
for (int i : arr) {
std::cout << i << " ";
}
// Output: 1 2 3 4
return 0;
}
Another thing to note is,
arrays are zero-indexed, which means the first element is at index 0, the second element is at index 1, and so on. The length property (or equivalent) of an array provides the total number of elements in the array.
When you add an element to the end of an array, you place it at the index equal to the current length of the array because:
1.The indices of the existing elements range from 0 to length - 1.
2.The next available position is at the index length.
so, we just have to directly add or assign the element at the length index slash next available index.
Now, its time to make rough draft of our algorithm, first initialize function cause we are making a function, let’s name it push taking two parameters array and element to add. Then assign element to array at next available index that would be length of an array. Finally, return array’s length.
Pseudocode:
- Initialize function named push
- assign element to array at next available index (length)
- return array’s length
Here a flowchart representation of our algorithm: nothing complex
Now let’s code it up with javaScript:
- The new element
ele
is added at the indexarr.length
, which is the next available position in the array. - The length of the array is incremented automatically.
- The function returns the new length of the array.
This custom push
function works similarly to the native Array.prototype.push
method. It modifies the original array and returns the new length of the array.
- Array.concat():
Next is array’s concat method. The concat method of Array instances is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.
So, how can we merge two arrays? If you think about it , merging an arrays is same as, taking individual elements and placing it in correct order into bigger array.
So, next logical step would be, if somehow expands the arrays into individual elements. And place them into larger array, then return that. that could work.
Now, the question is how to expands the arrays into individual elements? Well, let’s go home again, i mean the basics. In array, we have study about spread operator, which does exactly what we need, which is to expands the array into individual elements.
and to concatenate, place the spread arrays inside square brackets ,we create a new array that includes all elements from both arrays.
Now, time for annoying part or for some or most, the fun part, edge case. What if passed down arguments aren’t of type array. For that, just throw an error.
so, updating our algorithm, check if both arrays are of type array. If not, then throw an appropriate error like “Both arguments should be arrays”.
Pseudocode :
- initialize function named concat.
- check if both arrays are of type array
- If not, then throw an appropriate error
- return a array inside which, two spread array in placed
Here a flowchart representation of our algorithm: nothing complex
Now let’s code it up with javaScript:
The spread operator (...) in JavaScript allows an iterable such as an array to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected. This makes it a powerful tool for array manipulation, including concatenation.
How the Spread Operator Works
When you use the spread operator with arrays, it effectively breaks down the array into individual elements. This can then be used to create a new array containing elements from multiple arrays.
Example of Spread Operator for Concatenation
Here's an example to illustrate how the spread operator works for array concatenation:
const arr = [1, 2, 3];
const arr3 = [4, 5, 6];
// Using the spread operator to concatenate arrays
const concatenatedArray = [...arr, ...arr3];
console.log(concatenatedArray); // Output: [1, 2, 3, 4, 5, 6]
Step-by-Step Explanation
-
Spread Syntax: The spread operator
...arr
expands the arrayarr
into individual elements. Similarly,...arr3
expandsarr3
. -
Concatenation: By placing the spread arrays inside square brackets
[ ...arr, ...arr3 ]
, we create a new array that includes all elements from botharr
andarr3
.
Detailed Breakdown
Initial Arrays:
const arr = [1, 2, 3];
const arr3 = [4, 5, 6];-
Using Spread Operator:
const concatenatedArray = [...arr, ...arr3];
This is equivalent to:
const concatenatedArray = [1, 2, 3, 4, 5, 6];
-
Output:
console.log(concatenatedArray); // Output: [1, 2, 3, 4, 5, 6]
Implementation in a Function
Here's the complete code including a function to concatenate arrays with input validation:
function concat(arr, secondArray) {
// Check if both inputs are arrays
if (!Array.isArray(arr) || !Array.isArray(secondArray)) {
throw new TypeError('Both arguments should be arrays');
}
// Concatenate arrays using the spread operator
return [...arr, ...secondArray];
}
const arr = [1, 2, 3];
const arr3 = [4, 5, 6];
console.log(concat(arr, arr3)); // Output: [1, 2, 3, 4, 5, 6]
By leveraging the spread operator, array concatenation becomes more straightforward and intuitive.
Thank you for reading, that's all for today.
Top comments (0)