Manipulate Arrays with JavaScript Array Methods

CSSCSSBeginner
Practice Now

Introduction

In this lab, students will explore essential JavaScript array manipulation techniques through a comprehensive hands-on learning experience. The lab covers key array methods such as slice(), unshift(), shift(), sorting, and transforming arrays, providing practical skills for managing and modifying array data structures.

Participants will learn how to extract array elements using slice(), add elements to the beginning of an array with unshift(), remove the first element using shift(), and perform array sorting and reversal. By working through practical coding examples, learners will gain a solid understanding of how to effectively manipulate arrays in JavaScript, enhancing their programming capabilities and problem-solving skills.

Slice Array Elements

In this step, you'll learn how to use the slice() method to extract a portion of an array in JavaScript. The slice() method allows you to create a new array by selecting elements from an existing array without modifying the original array.

Let's start by creating a sample array and practicing how to slice its elements. Open the WebIDE and create a new file called array-slice.js in the ~/project directory.

// Create an array of fruits
const fruits = ["apple", "banana", "cherry", "date", "elderberry"];

// Slice the first three elements
const slicedFruits1 = fruits.slice(0, 3);
console.log("First three fruits:", slicedFruits1);

// Slice from index 2 to the end
const slicedFruits2 = fruits.slice(2);
console.log("Fruits from index 2:", slicedFruits2);

// Slice the last two elements using negative index
const slicedFruits3 = fruits.slice(-2);
console.log("Last two fruits:", slicedFruits3);

Now, run the script to see the results:

node ~/project/array-slice.js

Example output:

First three fruits: [ 'apple', 'banana', 'cherry' ]
Fruits from index 2: [ 'cherry', 'date', 'elderberry' ]
Last two fruits: [ 'date', 'elderberry' ]

Key points about slice():

  • The first argument is the start index (inclusive)
  • The second argument is the end index (exclusive)
  • If no end index is provided, it slices to the end of the array
  • Negative indices count from the end of the array
  • The original array remains unchanged

Add Elements to Array Head with unshift()

In this step, you'll learn how to use the unshift() method to add one or more elements to the beginning of an array in JavaScript. The unshift() method modifies the original array by inserting elements at the start and returns the new length of the array.

Create a new file called array-unshift.js in the ~/project directory and add the following code:

// Create an initial array of fruits
let fruits = ["banana", "cherry", "date"];
console.log("Original array:", fruits);

// Add a single element to the beginning of the array
fruits.unshift("apple");
console.log("After adding one element:", fruits);

// Add multiple elements to the beginning of the array
fruits.unshift("grape", "kiwi");
console.log("After adding multiple elements:", fruits);

// Store the new length of the array
let newLength = fruits.unshift("orange");
console.log("New array length:", newLength);
console.log("Final array:", fruits);

Now, run the script to see the results:

node ~/project/array-unshift.js

Example output:

Original array: [ 'banana', 'cherry', 'date' ]
After adding one element: [ 'apple', 'banana', 'cherry', 'date' ]
After adding multiple elements: [ 'grape', 'kiwi', 'apple', 'banana', 'cherry', 'date' ]
New array length: 7
Final array: [ 'orange', 'grape', 'kiwi', 'apple', 'banana', 'cherry', 'date' ]

Key points about unshift():

  • Adds one or more elements to the beginning of an array
  • Modifies the original array
  • Returns the new length of the array
  • Can add multiple elements in a single call
  • Shifts existing elements to higher indices

Remove First Element with shift()

In this step, you'll learn how to use the shift() method to remove the first element from an array in JavaScript. The shift() method modifies the original array by removing the first element and returns that removed element.

Create a new file called array-shift.js in the ~/project directory and add the following code:

// Create an initial array of programming languages
let languages = ["JavaScript", "Python", "Java", "C++", "Ruby"];
console.log("Original array:", languages);

// Remove and store the first element
let removedLanguage = languages.shift();
console.log("Removed language:", removedLanguage);
console.log("Array after shift:", languages);

// Remove multiple elements by calling shift() multiple times
let secondRemovedLanguage = languages.shift();
console.log("Second removed language:", secondRemovedLanguage);
console.log("Array after second shift:", languages);

// Demonstrate what happens with an empty array
let emptyArray = [];
let result = emptyArray.shift();
console.log("Shifting from an empty array:", result);
console.log("Empty array remains:", emptyArray);

Now, run the script to see the results:

node ~/project/array-shift.js

Example output:

Original array: [ 'JavaScript', 'Python', 'Java', 'C++', 'Ruby' ]
Removed language: JavaScript
Array after shift: [ 'Python', 'Java', 'C++', 'Ruby' ]
Second removed language: Python
Array after second shift: [ 'Java', 'C++', 'Ruby' ]
Shifting from an empty array: undefined
Empty array remains: []

Key points about shift():

  • Removes the first element from an array
  • Modifies the original array
  • Returns the removed element
  • Returns undefined if the array is empty
  • Reduces the array length by 1

Sort and Reverse Array Elements

In this step, you'll learn how to use the sort() and reverse() methods to manipulate array elements in JavaScript. These methods provide simple ways to organize and reorder array contents.

Create a new file called array-sort-reverse.js in the ~/project directory and add the following code:

// Create arrays for sorting demonstration
let numbers = [5, 2, 9, 1, 7];
let fruits = ["banana", "apple", "cherry", "date"];

// Default sorting (lexicographic for strings, ascending for numbers)
console.log("Original numbers:", numbers);
numbers.sort();
console.log("Default sort:", numbers);

// Numeric sorting requires a comparison function
numbers = [5, 2, 9, 1, 7];
numbers.sort((a, b) => a - b);
console.log("Numeric sort:", numbers);

// Reverse sorting
console.log("\nOriginal fruits:", fruits);
fruits.sort().reverse();
console.log("Sorted and reversed:", fruits);

// Reverse an array without sorting
let colors = ["red", "green", "blue", "yellow"];
console.log("\nOriginal colors:", colors);
colors.reverse();
console.log("Reversed colors:", colors);

Now, run the script to see the results:

node ~/project/array-sort-reverse.js

Example output:

Original numbers: [ 5, 2, 9, 1, 7 ]
Default sort: [ 1, 2, 5, 7, 9 ]
Numeric sort: [ 1, 2, 5, 7, 9 ]

Original fruits: [ 'banana', 'apple', 'cherry', 'date' ]
Sorted and reversed: [ 'date', 'cherry', 'banana', 'apple' ]

Original colors: [ 'red', 'green', 'blue', 'yellow' ]
Reversed colors: [ 'yellow', 'blue', 'green', 'red' ]

Key points about sort() and reverse():

  • sort() modifies the original array
  • Default sort() converts elements to strings and sorts lexicographically
  • Use a comparison function for numeric or custom sorting
  • reverse() reverses the order of elements in the array
  • Both methods work in-place, changing the original array

Transform and Analyze Arrays

In this step, you'll explore powerful array methods like map(), filter(), and reduce() to transform and analyze array elements in JavaScript. These methods provide elegant ways to manipulate and extract information from arrays.

Create a new file called array-transform.js in the ~/project directory and add the following code:

// Sample array of student scores
const scores = [85, 92, 78, 65, 90, 55, 88];

// Use map() to create a new array with modified values
const adjustedScores = scores.map((score) => score + 5);
console.log("Original scores:", scores);
console.log("Adjusted scores:", adjustedScores);

// Use filter() to create an array of passing scores (above 70)
const passingScores = scores.filter((score) => score >= 70);
console.log("Passing scores:", passingScores);

// Use reduce() to calculate the total sum of scores
const totalScore = scores.reduce((sum, score) => sum + score, 0);
const averageScore = totalScore / scores.length;
console.log("Total score:", totalScore);
console.log("Average score:", averageScore.toFixed(2));

// Combine methods: find average of passing scores
const averagePassingScore =
  passingScores.reduce((sum, score) => sum + score, 0) / passingScores.length;
console.log("Average passing score:", averagePassingScore.toFixed(2));

// Transform an array of names
const names = ["alice", "bob", "charlie"];
const capitalizedNames = names.map(
  (name) => name.charAt(0).toUpperCase() + name.slice(1)
);
console.log("Original names:", names);
console.log("Capitalized names:", capitalizedNames);

Now, run the script to see the results:

node ~/project/array-transform.js

Example output:

Original scores: [ 85, 92, 78, 65, 90, 55, 88 ]
Adjusted scores: [ 90, 97, 83, 70, 95, 60, 93 ]
Passing scores: [ 85, 92, 78, 90, 88 ]
Total score: 553
Average score: 79.00
Average passing score: 86.60
Original names: [ 'alice', 'bob', 'charlie' ]
Capitalized names: [ 'Alice', 'Bob', 'Charlie' ]

Key points about array transformation methods:

  • map(): Creates a new array by transforming each element
  • filter(): Creates a new array with elements that pass a test
  • reduce(): Reduces array to a single value through a callback function
  • These methods do not modify the original array
  • Can be chained together for complex transformations

Summary

In this lab, participants explored various JavaScript array manipulation techniques using built-in methods. The lab focused on learning how to slice array elements using the slice() method, which allows extracting specific portions of an array without modifying the original array. Participants practiced creating new arrays by selecting elements using different index ranges, including positive and negative indices.

The lab also introduced methods like unshift() for adding elements to the beginning of an array, shift() for removing the first element, and techniques for sorting and reversing array elements. Through hands-on coding exercises, learners gained practical experience in transforming and analyzing arrays, understanding how these methods can efficiently modify and extract data from array structures in JavaScript.