Mastering JavaScript Arrays: A Complete Guide to Creation, Manipulation, Filtering, and Practical Applications

目次

1. Introduction

What Are JavaScript Arrays and Why Are They Important?

JavaScript arrays are one of the essential elements for efficiently managing and manipulating data. By using arrays, you can store multiple values in a single variable and retrieve or modify them as needed. For example, arrays are extremely useful when saving a list of usernames, a product list, or calculation results. Especially in web application development, arrays are frequently used when handling form data or data retrieved from APIs.

Practical Use Cases of Arrays

  • List Management: Managing shopping cart items or a to-do list.
  • Data Filtering: User search and sorting features.
  • Animation Control: Managing element order or dynamic changes.
Arrays are a foundational structure for handling grouped data and are an essential topic when learning JavaScript.

What You Will Learn in This Article

This article systematically explains JavaScript arrays, covering topics such as:
  1. How to declare and initialize arrays
  2. How to add, remove, and retrieve elements
  3. Sorting and filtering techniques
  4. Methods for merging and splitting arrays
  5. Application examples using arrays
The content is suitable for beginners to intermediate learners and carefully explains everything from basics to practical techniques.

Who This Article Is For

  • Beginners: Those handling arrays for the first time.
  • Intermediate Users: Those who want to learn advanced operations or write more efficient code.
With code examples and practical use cases, even beginners can learn confidently.

What You Can Achieve by Learning Arrays

Once you master JavaScript arrays, you will gain the following skills:
  • Data Management & Manipulation: Easily add, remove, or sort data.
  • API Integration: Efficiently handle and display data retrieved from Web APIs.
  • Application Development: Build simple apps using practical examples.
Use what you learn here to build more advanced JavaScript applications.

2. Array Basics | Declaration and Initialization

2.1 Definition and Role of Arrays

JavaScript arrays are special objects that allow you to manage multiple data items at once. Each element has an index that determines its position, making data retrieval and manipulation easy.

Main Roles of Arrays

  1. List Management: Managing grouped data such as product lists or user information.
  2. Data Manipulation: Performing efficient tasks such as sorting or searching.
  3. Dynamic Data Processing: Handling and transforming data retrieved from APIs.

Array Characteristics

  • Element indices start from 0.
  • Values of different data types can be stored together.
let mixedArray = [1, "hello", true];
console.log(mixedArray[1]); // "hello"

2.2 Declaring and Initializing Arrays

Basic Array Declaration

In JavaScript, arrays can be declared in two ways:
  1. Using literal notation (recommended)
let fruits = ["apple", "banana", "grape"];
  1. Using the Array constructor
let fruits = new Array("apple", "banana", "grape");

Creating an Empty Array

let emptyArray = [];

2.3 Declaring Multidimensional Arrays

A multidimensional array is an array that contains other arrays. It is useful when managing hierarchical data structures.
let matrix = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];

console.log(matrix[1][2]); // 6

2.4 Notes on Initialization

Mixing Data Types

JavaScript arrays can store values of different data types, which may cause unexpected errors if not handled carefully.
let mixed = [1, "text", true];
console.log(typeof mixed[0]); // "number"
console.log(typeof mixed[1]); // "string"
console.log(typeof mixed[2]); // "boolean"

2.5 Basic Array Operation Examples

let animals = ["dog", "cat", "bird"];
console.log(animals[0]); // "dog"

animals.push("rabbit");
console.log(animals); // ["dog", "cat", "bird", "rabbit"]

animals[1] = "lion";
console.log(animals); // ["dog", "lion", "bird", "rabbit"]

Summary

This section explained the following concepts about JavaScript arrays:
  1. Definition and roles of arrays
  2. Basic syntax for declaration and initialization
  3. Multidimensional arrays and length handling
  4. Important considerations during initialization with code examples
With this knowledge, you will be better prepared for the next step: “Basic Array Operations.”

3. Basic Array Operations | Adding, Removing, and Retrieving Elements

3.1 Methods for Adding Elements

Add Elements to the End – push()

let fruits = ["apple", "banana"];
fruits.push("orange");
console.log(fruits); // ["apple", "banana", "orange"]

Add Elements to the Beginning – unshift()

let animals = ["cat", "dog"];
animals.unshift("rabbit");
console.log(animals); // ["rabbit", "cat", "dog"]

3.2 Methods for Removing Elements

Remove the Last Element – pop()

let colors = ["red", "blue", "green"];
let removed = colors.pop();
console.log(colors); // ["red", "blue"]
console.log(removed); // "green"

Remove the First Element – shift()

let numbers = [1, 2, 3, 4];
let removedNumber = numbers.shift();
console.log(numbers); // [2, 3, 4]
console.log(removedNumber); // 1

Remove Elements from Any Position – splice()

let sports = ["soccer", "baseball", "basketball", "tennis"];
sports.splice(1, 2);
console.log(sports); // ["soccer", "tennis"]

3.3 Methods for Retrieving Elements

Retrieve by Index

let drinks = ["water", "tea", "coffee"];
console.log(drinks[0]); // "water"
console.log(drinks[2]); // "coffee"

Retrieve the Last Element

let cities = ["Tokyo", "Osaka", "Kyoto"];
console.log(cities[cities.length - 1]); // "Kyoto"

Retrieve the First Matching Element – find()

let numbers = [10, 20, 30, 40];
let result = numbers.find(num => num > 25);
console.log(result); // 30

Summary

In this section, we explained the following JavaScript array operations:
  1. How to add elements (push() and unshift())
  2. How to remove elements (pop(), shift(), splice())
  3. How to retrieve elements (index access, find(), includes())
By combining these basic operations, you can freely manipulate arrays.

4. Sorting and Filtering Arrays

4.1 Methods for Sorting Arrays

Sort in Ascending or Descending Order – sort()

let numbers = [40, 10, 30, 20];
numbers.sort((a, b) => a - b);
console.log(numbers); // [10, 20, 30, 40]

Reverse the Order – reverse()

let letters = ["a", "b", "c", "d"];
letters.reverse();
console.log(letters); // ["d", "c", "b", "a"]

4.2 Methods for Filtering Arrays

Extract Elements that Match a Condition – filter()

let numbers = [1, 2, 3, 4, 5, 6];
let evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // [2, 4, 6]

Retrieve the First Element that Matches a Condition – find()

let ages = [15, 20, 25, 30];
let firstAdult = ages.find(age => age >= 20);
console.log(firstAdult); // 20

Get Index of the First Matching Element – findIndex()

let scores = [50, 70, 85, 40];
let highScoreIndex = scores.findIndex(score => score > 80);
console.log(highScoreIndex); // 2

Summary

This section explained how to sort and filter arrays in JavaScript:
  1. Sorting: Using sort() and reverse() to control order.
  2. Filtering: Using filter() to extract matching elements.
  3. Searching: Using find() and findIndex() to locate elements.

5. Joining, Splitting, and Transforming Arrays

5.1 Methods for Joining Arrays

Join Arrays – concat()

let fruits = ["apple", "banana"];
let vegetables = ["carrot", "spinach"];
let combined = fruits.concat(vegetables);
console.log(combined); // ["apple", "banana", "carrot", "spinach"]

Join Using the Spread Syntax

let fruits = ["apple", "banana"];
let vegetables = ["carrot", "spinach"];
let combined = [...fruits, ...vegetables];
console.log(combined); // ["apple", "banana", "carrot", "spinach"]

5.2 Methods for Splitting Arrays

Extract a Portion – slice()

let colors = ["red", "blue", "green", "yellow", "purple"];
let selectedColors = colors.slice(1, 4);
console.log(selectedColors); // ["blue", "green", "yellow"]

Remove or Replace Elements – splice()

let languages = ["JavaScript", "Python", "Ruby", "Java"];
languages.splice(1, 2);
console.log(languages); // ["JavaScript", "Java"]

5.3 Methods for Transforming Arrays

Convert Array to String – join()

let items = ["apple", "banana", "grape"];
let result = items.join(", ");
console.log(result); // "apple, banana, grape"

Convert String to Array – split()

let str = "apple,banana,grape";
let arr = str.split(",");
console.log(arr); // ["apple", "banana", "grape"]

Flatten a Multidimensional Array – flat()

let numbers = [1, [2, 3], [4, [5, 6]]];
let flatNumbers = numbers.flat(2);
console.log(flatNumbers); // [1, 2, 3, 4, 5, 6]

Summary

This section explained various JavaScript array methods for joining, splitting, and transforming arrays:
  1. Joining arrays: concat() and spread syntax
  2. Splitting arrays: slice() for extraction and splice() for removal or replacement
  3. Transforming arrays: join() and split() for string conversion
  4. Flattening: flat() for converting nested arrays into a single dimension

6. Looping Through Arrays and Advanced Techniques

6.1 Methods for Looping Through Arrays

Basic Looping with for

let fruits = ["apple", "banana", "grape"];
for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i]);
}
// Output: apple, banana, grape

Simplified Looping with for...of

let colors = ["red", "blue", "green"];
for (let color of colors) {
  console.log(color);
}
// Output: red, blue, green

Looping with the forEach() Method

let animals = ["cat", "dog", "bird"];
animals.forEach((animal, index) => {
  console.log(`${index}: ${animal}`);
});
// Output: 0: cat, 1: dog, 2: bird

Create a New Array with map()

let numbers = [1, 2, 3, 4];
let doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6, 8]

6.2 Advanced Techniques

Remove Duplicate Elements

let numbers = [1, 2, 2, 3, 4, 4, 5];
let uniqueNumbers = [...new Set(numbers)];
console.log(uniqueNumbers); // [1, 2, 3, 4, 5]

Flatten an Array – flat()

let nested = [1, [2, 3], [4, [5, 6]]];
let flatArray = nested.flat(2);
console.log(flatArray); // [1, 2, 3, 4, 5, 6]

Summary

This section explained array looping methods and advanced techniques:
  1. Basic loops: Efficient iteration using for and for...of.
  2. Method-based loops: Using forEach() and map() for cleaner and more functional processing.
  3. Advanced data manipulation: Removing duplicates and flattening nested arrays.

7. Practical Example | Building a Simple Application Using Arrays

7.1 Creating a To-Do List Application

Feature Overview

This simple To-Do list app includes the following features:
  1. Add new tasks
  2. Remove completed tasks
  3. Display the current list of tasks

Code Example

let tasks = [];

// Function to add a new task
function addTask(task) {
  tasks.push(task);
  console.log(`Added: ${task}`);
  displayTasks();
}

// Function to remove a task
function removeTask(index) {
  if (index >= 0 && index < tasks.length) { let removed = tasks.splice(index, 1); console.log(`Removed: ${removed[0]}`); displayTasks(); } else { console.log("Invalid index"); } } // Function to display current tasks function displayTasks() { console.log("Current Tasks:"); tasks.forEach((task, index) => {
    console.log(`${index + 1}: ${task}`);
  });
}

// Test execution
addTask("Study JavaScript");
addTask("Create shopping list");
addTask("Check email");

removeTask(1); // Remove the second task

Example Output

Added: Study JavaScript
Added: Create shopping list
Added: Check email
Current Tasks:
1: Study JavaScript
2: Create shopping list
3: Check email
Removed: Create shopping list
Current Tasks:
1: Study JavaScript
2: Check email

Summary

This section introduced a practical application using array operations:
  1. To-Do List Application: Practiced adding, removing, and displaying tasks.
  2. Search and Data Analysis: Demonstrated how to implement flexible search and data aggregation using array operations.

8. Summary | Mastering Array Operations

JavaScript arrays are powerful tools that help streamline data management and manipulation. This article covered everything from basic operations to advanced techniques and practical examples.

8.1 Review of This Article

1. Basic Array Operations

  • Declaration and Initialization: Learned how to create arrays and handle multidimensional arrays.
  • Adding, Removing, and Retrieving Elements: Practiced dynamic data manipulation using methods like push(), pop(), and others.

2. Sorting and Filtering Arrays

  • Sorting: Explained how to modify array order using sort() and reverse().
  • Filtering: Learned how to extract data using filter() and find().

3. Joining, Splitting, and Transforming Arrays

  • Joining: Understood how to merge arrays using concat() and spread syntax.
  • Splitting & Transforming: Used slice(), splice(), join(), and split() for flexible data handling.

4. Looping and Advanced Techniques

  • Looping: Used for, forEach(), and map() for efficient iteration.
  • Advanced Techniques: Learned to remove duplicates and flatten nested arrays.

5. Practical Examples

  • To-Do List App: Applied array operations to build a functional app.
  • Search & Data Aggregation: Demonstrated practical data filtering and analysis.

8.2 Importance of Array Operations and Use Cases

Why Are Array Operations Important?

Array manipulation is essential for organizing, analyzing, and displaying data. Common scenarios include:
  1. Data Management and Display: Filtering API data and showing results in tables.
  2. Form and User Input Handling: Dynamically updating lists or processing input values.
  3. Search and Sorting Functions: Handling large datasets efficiently.
  4. Application Development: Building UI features like shopping carts and task managers.

8.3 Next Steps in Learning

1. Further Use of Array Methods

  • Suggested Task: Build an app that fetches API data and filters the results using array operations.

2. Compare and Use Other Data Structures

  • Learn Objects, Set, and Map to choose the right structure for each scenario.

3. Apply Knowledge in JavaScript Frameworks

  • Use array skills in frameworks like React or Vue.js for real-world development.

8.4 Reference Links and Resources

8.5 Final Thoughts and Advice for Readers

JavaScript array operations are essential for building a solid programming foundation. This article provided a structured approach from basics to advanced concepts.

Advice

  1. Practice by writing code: Test each method to deepen your understanding.
  2. Develop problem-solving skills: Convert real-world tasks into programs to enhance practical expertise.
  3. Continue learning: Learn new frameworks and latest technologies to improve your skill set.

Take the Next Step!

Use this article as a foundation to advance toward building more complex applications or learning modern frameworks.

FAQ | Frequently Asked Questions

Q1. What is the difference between map() and forEach()?

  • map(): Returns a new array after applying a function to each element.
  • forEach(): Executes a function for each element but does not return a new array.
Example:
let numbers = [1, 2, 3];

// map()
let doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6]

// forEach()
numbers.forEach(num => console.log(num * 2));
// Output: 2, 4, 6

Q2. How do I sort numbers correctly?

By default, sort() compares values as strings. To sort numbers numerically, you must pass a comparison function. Example:
let numbers = [40, 100, 1, 5, 25];
numbers.sort((a, b) => a - b);
console.log(numbers); // [1, 5, 25, 40, 100]

Q3. How can I remove duplicates from an array?

Use the Set object to remove duplicates easily. Example:
let numbers = [1, 2, 2, 3, 4, 4, 5];
let uniqueNumbers = [...new Set(numbers)];
console.log(uniqueNumbers); // [1, 2, 3, 4, 5]

Q4. How do I check if an element exists in an array?

Use the includes() method to determine whether the array contains a specific value. Example:
let fruits = ["apple", "banana", "grape"];
console.log(fruits.includes("banana")); // true
console.log(fruits.includes("melon")); // false

Q5. How do I flatten a multidimensional array?

Use the flat() method to convert a nested array into a single-level array. Example:
let nested = [1, [2, 3], [4, [5, 6]]];
let flatArray = nested.flat(2);
console.log(flatArray); // [1, 2, 3, 4, 5, 6]
広告