Posts.

5 Array Methods | Part 2 | Mastering JavaScript

Cover Image for 5 Array Methods | Part 2 | Mastering JavaScript
Rami Al-Karo
Rami Al-Karo

Hey and welcome to another video in Mastering JavaScript series in this video we gonna take look into another 5 array methods and they are shift, unshift, concat, slice, and splice. understanding each one use cases, if you miss the first part link the video description which consist of push, pop, find, isArray and some.

shift

The shift() method in JavaScript, is used to remove the first element from the array and return that removed element. Additionally, it modifies the original array by removing the element, which also results in the array's length being decreased by 1. This method works like the "pop" method, which removes an element from an array. The key difference is that "pop" removes the last element, while "shift" removes it from the first element.

1 2 3 4 5 6 // Easy Example let colors = ["red", "green", "blue"]; let removedColor = colors.shift(); console.log("Removed color:", removedColor); // Output: "red" console.log("Updated array:", colors); // Output: ["green", "blue"]

In this easy example, we have an array of colors, and we use shift() to remove the first color ("red") from the colors array. The removed color is stored in the removedColor variable, and the array is updated to contain only ["green", "blue"].

1 2 3 4 5 6 7 8 9 10 11 12 // Advanced Example function processQueue(queue) { while (queue.length > 0) { let task = queue.shift(); console.log("Processing task:", task); // Perform some advanced processing on the task } console.log("Queue is empty."); } let taskQueue = ["Task 1", "Task 2", "Task 3", "Task 4"]; processQueue(taskQueue);

In this advanced example, we have a custom function processQueue that takes an array of tasks. It continuously processes tasks from the queue using shift() until the queue is empty. The function simulates advanced processing for each task.

When we call function with the array, which removes and processes tasks from the front of the queue until there are no tasks left. Showing how the shift() method can be used in more complex scenarios, such as managing task queues or processing data in a specific order.


unshift

The unshift() method in JavaScript is used to add one or more specified elements to the beginning of an array and returns the new length of the array after adding those elements. It modifies the original array by adding elements to the front. This method work same as the "push" method, which adds a new element to an array. The main distinction is that "push" appends an element to the end of the array, while "unshift" adds it to the beginning.

1 2 3 4 5 6 // Easy Example let colors = ["green", "blue"]; let newLength = colors.unshift("red"); console.log("New length:", newLength); // Output: 3 console.log("Updated array:", colors); // Output: ["red", "green", "blue"]

In this easy example, we have an array of colors, and we use unshift("red") to add the color "red" to the beginning of the colors array. It returns the new length of the array and updates the array to be ["red", "green", "blue"].

1 2 3 4 5 6 7 8 9 10 11 12 13 // Advanced Example function mergeArrays(arr1, arr2) { for (let i = arr2.length - 1; i >= 0; i--) { arr1.unshift(arr2[i]); } return arr1; } let array1 = [1, 2, 3]; let array2 = [4, 5, 6]; let mergedArray = mergeArrays(array1, array2); console.log("Merged array:", mergedArray); // Output: [4, 5, 6, 1, 2, 3]

In this advanced example, we have a custom function mergeArrays that takes two arrays and merges them by using the unshift() method. It iterates through second array in reverse order and adds its elements to the front of first array.

When we call mergeArrays with arrays as arguments it effectively merges the two arrays, resulting in merge one. This example show how the unshift() method can be used in more complex scenarios, such as combining arrays in a specific order.


concat

The concat() method in JavaScript is used to merge two or more arrays together. It doesn't modify the existing arrays but instead returns a new array containing the concatenated elements of the original arrays

1 2 3 4 5 6 // Easy Example let fruits1 = ["apple", "banana"]; let fruits2 = ["orange", "grape"]; let combinedFruits = fruits1.concat(fruits2); console.log("Combined fruits:", combinedFruits); // Output: ["apple", "banana", "orange", "grape"]

In this easy example, we have two arrays, fruits1 and fruits2, which represent different sets of fruits. We use concat() to combine these arrays into one. As a result, we get a new array containing all the fruits from both original arrays.

1 2 3 4 5 6 7 8 9 10 11 // Advanced Example function mergeArrays(...arrays) { return [].concat(...arrays); } let array1 = [1, 2, 3]; let array2 = [4, 5]; let array3 = [6, 7, 8]; let mergedArray = mergeArrays(array1, array2, array3); console.log("Merged array:", mergedArray); // Output: [1, 2, 3, 4, 5, 6, 7, 8]

In this advanced example, we have a custom function mergeArrays that accepts a variable number of arrays using the spread operator (...arrays). Inside the function, we use concat() to merge all the arrays into a single array and return the result.

When we call mergeArrays with list of arrays, it effectively combines the elements from all arrays into one. This example show how the concat() method can be used to merge an variety number of arrays together.


slice

The slice() method in JavaScript is used to extract a shallow copy of a portion of an array into a new array. This copy is selected based on the start and end indices provided as arguments, something to clarify that, the end index is not included and the original array is not modified; slice() returns a new array with the selected elements.

1 2 3 4 5 6 // Easy Example let numbers = [1, 2, 3, 4, 5]; let slicedNumbers = numbers.slice(1, 4); console.log("Sliced array:", slicedNumbers); // Output: [2, 3, 4] console.log("Original array:", numbers); // Output: [1, 2, 3, 4, 5] (unchanged)

In this easy example, we have an array of numbers, and we use slice(1, 4) to extract a portion of the array, starting from index 1 ("2") and ending just before index 4 ("5"). It returns a new array, slicedNumbers, containing the selected elements. The original numbers array remains the same.

1 2 3 4 5 6 7 8 9 10 11 12 // Advanced Example function getTopNItems(arr, n) { if (n <= 0) { return []; } return arr.slice(0, n); } let items = ["apple", "banana", "cherry", "date", "fig"]; let topThreeItems = getTopNItems(items, 3); console.log("Top three items:", topThreeItems); // Output: ["apple", "banana", "cherry"]

In this advanced example, we have a custom function getTopNItems that takes an array and a number n. It returns a new array containing the top n items from the input array. The function uses the slice() method to achieve this.

When we call getTopNItems(items, 3), it extracts the top three items from the items array and returns ["apple", "banana", "cherry"]. This example show how the slice() method can be used in more complex scenarios, such as retrieving a specific number of items from a list.


splice

The final method is the splice() method, in JavaScript is used to modify the contents of an array by removing or replacing existing elements and/or adding new elements in place. It provides a flexible way to edit arrays in various ways.

1 2 3 4 5 6 // Easy Example let colors = ["red", "green", "blue", "yellow", "purple"]; let removedColors = colors.splice(2, 2); // Remove 2 elements starting from index 2 console.log("Removed colors:", removedColors); // Output: ["blue", "yellow"] console.log("Updated array:", colors); // Output: ["red", "green", "purple"] (elements "blue" and "yellow" are removed)

let say that we have an array of colors, and we use splice(2, 2) which mean that we gonna removes two elements starting from index 2 ("blue" and "yellow"). The removed elements are saved in variable removedColors, and the original colors array is updated.

1 2 3 4 5 6 7 8 9 10 // Advanced Example function insertElementAtIndex(arr, index, element) { arr.splice(index, 0, element); return arr; } let numbers = [1, 2, 4, 5]; insertElementAtIndex(numbers, 2, 3); // Insert 3 at index 2 console.log("Updated array:", numbers); // Output: [1, 2, 3, 4, 5]

another example we gonna create function insertElementAtIndex that takes an array (arr), an index (index), and an element (element). The function uses splice() to insert the specified element at the given index without remove any elements.

When we call insertElementAtIndex(numbers, 2, 3), it inserts the number "3" at index 2 in the numbers array. This show how the splice() method can be used for more complex operations, such as inserting elements at specific positions in an array.


Thank you for taking the time to explore the concepts of shift, unshift, concat, slice, and splice with me. I hope you found these examples and explanations helpful in understanding.

do not forget to like and subscribe, stay tuned for more videos and content. see you in the next one.


More Stories

Cover Image for  5 Array Methods in JavaScript | Part 3 | Mastering JavaScript

5 Array Methods in JavaScript | Part 3 | Mastering JavaScript

485 words - 2,754 characters

Rami Al-Karo
Rami Al-Karo
Cover Image for  5 Array Methods in JavaScript | Part 1 | Mastering JavaScript

5 Array Methods in JavaScript | Part 1 | Mastering JavaScript

500 words - 3,806 characters

Rami Al-Karo
Rami Al-Karo