2. Building JavaScript Array Methods from Scratch in 2024 – Easy tutorial for beginners.

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 method…


This content originally appeared on DEV Community and was authored by itric

Video version link: https://www.youtube.com/watch?v=3DE4-o23tPc

Image description
Continuing our series of building javaScript method from Scratch for beginners, in this blog we will be making these 2 methods :

  1. Array.push()

  2. 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,

Image description
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.

  1. 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.

Image description
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:

  1. 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.
  2. 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.
  3. 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.

Image description
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

Image description

Here a flowchart representation of our algorithm: nothing complex

Image description
Now let’s code it up with javaScript:

Image description

Image description

Image description
In this implementation:

  1. The new element ele is added at the index arr.length, which is the next available position in the array.
  2. The length of the array is incremented automatically.
  3. 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.

  1. 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.

Image description
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.

Image description
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

Image description
Here a flowchart representation of our algorithm: nothing complex

Image description
Now let’s code it up with javaScript:

Image description

Image description

Image description

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

  1. Spread Syntax: The spread operator ...arr expands the array arr into individual elements. Similarly, ...arr3 expands arr3.
  2. Concatenation: By placing the spread arrays inside square brackets [ ...arr, ...arr3 ], we create a new array that includes all elements from both arr and arr3.

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.


This content originally appeared on DEV Community and was authored by itric


Print Share Comment Cite Upload Translate Updates
APA

itric | Sciencx (2024-06-19T08:05:48+00:00) 2. Building JavaScript Array Methods from Scratch in 2024 – Easy tutorial for beginners.. Retrieved from https://www.scien.cx/2024/06/19/2-building-javascript-array-methods-from-scratch-in-2024-easy-tutorial-for-beginners/

MLA
" » 2. Building JavaScript Array Methods from Scratch in 2024 – Easy tutorial for beginners.." itric | Sciencx - Wednesday June 19, 2024, https://www.scien.cx/2024/06/19/2-building-javascript-array-methods-from-scratch-in-2024-easy-tutorial-for-beginners/
HARVARD
itric | Sciencx Wednesday June 19, 2024 » 2. Building JavaScript Array Methods from Scratch in 2024 – Easy tutorial for beginners.., viewed ,<https://www.scien.cx/2024/06/19/2-building-javascript-array-methods-from-scratch-in-2024-easy-tutorial-for-beginners/>
VANCOUVER
itric | Sciencx - » 2. Building JavaScript Array Methods from Scratch in 2024 – Easy tutorial for beginners.. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/06/19/2-building-javascript-array-methods-from-scratch-in-2024-easy-tutorial-for-beginners/
CHICAGO
" » 2. Building JavaScript Array Methods from Scratch in 2024 – Easy tutorial for beginners.." itric | Sciencx - Accessed . https://www.scien.cx/2024/06/19/2-building-javascript-array-methods-from-scratch-in-2024-easy-tutorial-for-beginners/
IEEE
" » 2. Building JavaScript Array Methods from Scratch in 2024 – Easy tutorial for beginners.." itric | Sciencx [Online]. Available: https://www.scien.cx/2024/06/19/2-building-javascript-array-methods-from-scratch-in-2024-easy-tutorial-for-beginners/. [Accessed: ]
rf:citation
» 2. Building JavaScript Array Methods from Scratch in 2024 – Easy tutorial for beginners. | itric | Sciencx | https://www.scien.cx/2024/06/19/2-building-javascript-array-methods-from-scratch-in-2024-easy-tutorial-for-beginners/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.