Arrays in JavaScript
What Is an Array?
An array is a data structure used to store a collection of elements in a single variable. The elements can be of the same data type or of different types.
// Creating an array
let courseList = ["Web Programming", "Database", "Algorithms"];
let examScores = [85, 90, 78, 92, 88];
let mixed = ["John", 3.75, true, null];
// Accessing an element (index starts at 0)
console.log(courseList[0]); // "Web Programming"
console.log(courseList[2]); // "Algorithms"
// Array length
console.log(courseList.length); // 3
// Modifying an element
courseList[1] = "Advanced Database";
console.log(courseList); // ["Web Programming", "Advanced Database", "Algorithms"]
Creating Arrays
// Method 1: Array literal (most common)
let arr1 = [1, 2, 3, 4, 5];
// Method 2: Constructor
let arr2 = new Array(1, 2, 3, 4, 5);
// Method 3: Array.of()
let arr3 = Array.of(1, 2, 3);
// Method 4: Array.from()
let arr4 = Array.from("John"); // ["B", "u", "d", "i"]
// Method 5: Spread operator
let arr5 = [..."John"]; // ["B", "u", "d", "i"]
// Empty array
let empty = [];
let empty2 = new Array(5); // Array with 5 empty slots
Methods — Mutating (Modify the Original Array)
push() — Add to the End
let courseList = ["Web Programming", "Database"];
courseList.push("Algorithms");
console.log(courseList); // ["Web Programming", "Database", "Algorithms"]
courseList.push("Computer Networks", "English");
console.log(courseList); // [..., "Computer Networks", "English"]
console.log(courseList.length); // 5
pop() — Remove from the End
let courseList = ["Web Programming", "Database", "Algorithms"];
const last = courseList.pop();
console.log(last); // "Algorithms"
console.log(courseList); // ["Web Programming", "Database"]
shift() — Remove from the Beginning
let courseList = ["Web Programming", "Database", "Algorithms"];
const first = courseList.shift();
console.log(first); // "Web Programming"
console.log(courseList); // ["Database", "Algorithms"]
unshift() — Add to the Beginning
let courseList = ["Database", "Algorithms"];
courseList.unshift("Web Programming");
console.log(courseList); // ["Web Programming", "Database", "Algorithms"]
splice() — Remove/Add at a Specific Position
let courseList = ["Web Programming", "Database", "Algorithms", "Computer Networks"];
// Remove 1 element at index 1
const removed = courseList.splice(1, 1);
console.log(removed); // ["Database"]
console.log(courseList); // ["Web Programming", "Algorithms", "Computer Networks"]
// Add elements at index 1
courseList.splice(1, 0, "Database", "Artificial Intelligence");
console.log(courseList); // ["Web Programming", "Database", "Artificial Intelligence", "Algorithms", "Computer Networks"]
// Replace elements at index 1
courseList.splice(1, 2, "New Database");
console.log(courseList); // ["Web Programming", "New Database", "Algorithms", "Computer Networks"]
sort() — Sorting
// Sort letters (default: lexicographic)
let names = ["John", "Mike", "Dana", "Anna"];
names.sort();
console.log(names); // ["Mike", "John", "Anna", "Dana"]
// Sort numbers — CAREFUL! The default sort treats them as strings
let scores = [85, 90, 78, 92, 88];
scores.sort();
console.log(scores); // [78, 85, 88, 90, 92] — happens to be correct
// Correct number sort (using a compare function)
let scores2 = [100, 85, 900, 78, 92];
scores2.sort((a, b) => a - b); // Ascending
console.log(scores2); // [78, 85, 92, 100, 900]
scores2.sort((a, b) => b - a); // Descending
console.log(scores2); // [900, 100, 92, 85, 78]
// Sort objects
const students = [
{ name: "John", gpa: 3.75 },
{ name: "Mike", gpa: 3.50 },
{ name: "Anna", gpa: 3.90 }
];
students.sort((a, b) => b.gpa - a.gpa);
console.log(students);
// [{ name: "Anna", gpa: 3.90 }, { name: "John", gpa: 3.75 }, ...]
reverse() — Reversing the Order
let scores = [85, 90, 78, 92, 88];
scores.reverse();
console.log(scores); // [88, 92, 78, 90, 85]
Methods — Non-Mutating (Do Not Modify the Original Array)
slice() — Extracting a Portion
let courseList = ["Web Programming", "Database", "Algorithms", "Computer Networks", "English"];
// Get from index 1 up to 3 (excluding 3)
const sliced = courseList.slice(1, 3);
console.log(sliced); // ["Database", "Algorithms"]
// Get from index 2 to the end
const from2 = courseList.slice(2);
console.log(from2); // ["Algorithms", "Computer Networks", "English"]
// Copy an array
const copy = courseList.slice();
console.log(copy); // ["Web Programming", "Database", "Algorithms", "Computer Networks", "English"]
concat() — Joining Arrays
let semester1 = ["Web Programming", "Database"];
let semester2 = ["Algorithms", "Computer Networks"];
let allCourses = semester1.concat(semester2);
console.log(allCourses); // ["Web Programming", "Database", "Algorithms", "Computer Networks"]
// With the spread operator
let allCourses2 = [...semester1, ...semester2];
includes() — Checking for the Presence of an Element
let courseList = ["Web Programming", "Database", "Algorithms"];
console.log(courseList.includes("Database")); // true
console.log(courseList.includes("Artificial Intelligence")); // false
indexOf() and lastIndexOf() — Finding a Position
let courseList = ["Web Programming", "Database", "Algorithms", "Database"];
console.log(courseList.indexOf("Database")); // 1 (first)
console.log(courseList.lastIndexOf("Database")); // 3 (last)
console.log(courseList.indexOf("Computer Networks")); // -1 (not found)
find() — Finding the First Matching Element
const studentList = [
{ studentId: "2024100123", name: "John Smith", gpa: 3.75 },
{ studentId: "2024100124", name: "Mike Brown", gpa: 3.50 },
{ studentId: "2024100125", name: "Anna Green", gpa: 3.90 }
];
const john = studentList.find(m => m.name.includes("John"));
console.log(john); // { studentId: "2024100123", name: "John Smith", gpa: 3.75 }
const notFound = studentList.find(m => m.name.includes("Eric"));
console.log(notFound); // undefined
findIndex() — Finding the First Matching Index
const index = studentList.findIndex(m => m.name.includes("Mike"));
console.log(index); // 1
filter() — Filtering Elements
const scores = [85, 90, 78, 92, 88, 45, 55, 95];
// Filter scores >= 80
const goodScores = scores.filter(n => n >= 80);
console.log(goodScores); // [85, 90, 92, 88, 95]
// Filtering in an academic portal
const students = [
{ name: "John", gpa: 3.75, status: "active" },
{ name: "Mike", gpa: 3.50, status: "active" },
{ name: "Anna", gpa: 1.75, status: "suspended" },
{ name: "Dana", gpa: 3.20, status: "active" }
];
const activeStudents = students.filter(m => m.status === "active");
console.log(activeStudents); // 3 active students
const cumLaude = students.filter(m => m.gpa >= 3.5);
console.log(cumLaude); // [{ name: "John", ... }, { name: "Mike", ... }]
map() — Transforming Each Element
const scores = [85, 90, 78, 92, 88];
// Add a bonus of 5 to every score
const bonusScores = scores.map(n => n + 5);
console.log(bonusScores); // [90, 95, 83, 97, 93]
// Change the format
const formattedScores = scores.map(n => ({
score: n,
grade: n >= 90 ? "A" : n >= 80 ? "B" : n >= 70 ? "C" : "D"
}));
console.log(formattedScores);
// In an academic portal: get the names only
const studentList = [
{ studentId: "2024100123", name: "John Smith" },
{ studentId: "2024100124", name: "Mike Brown" }
];
const names = studentList.map(m => m.name);
console.log(names); // ["John Smith", "Mike Brown"]
reduce() — Accumulating a Value
const scores = [85, 90, 78, 92, 88];
// Sum all scores
const total = scores.reduce((accumulator, currentValue) => {
return accumulator + currentValue;
}, 0); // 0 is the initial accumulator value
console.log(total); // 433
// Average
const average = total / scores.length;
console.log(average); // 86.6
// In an academic portal: calculate total credit units
const courseList = [
{ name: "Web Programming", credits: 3 },
{ name: "Database", credits: 3 },
{ name: "Algorithms", credits: 4 },
{ name: "Computer Networks", credits: 3 }
];
const totalCredits = courseList.reduce((sum, c) => sum + c.credits, 0);
console.log(`Total credits: ${totalCredits}`); // 13
// Calculate GPA
const gradeList = [
{ course: "Web Programming", score: 85, credits: 3 },
{ course: "Database", score: 78, credits: 3 },
{ course: "Algorithms", score: 92, credits: 4 }
];
const totalWeight = gradeList.reduce((sum, item) => {
const weight = item.score >= 85 ? 4 : item.score >= 80 ? 3.5 : item.score >= 75 ? 3 : 2;
return sum + (weight * item.credits);
}, 0);
const totalGpaCredits = gradeList.reduce((sum, item) => sum + item.credits, 0);
const gpa = totalWeight / totalGpaCredits;
console.log(`GPA: ${gpa.toFixed(2)}`); // GPA: 3.47
forEach() — Iterating Over Each Element
const courseList = ["Web Programming", "Database", "Algorithms"];
// forEach returns nothing (undefined)
courseList.forEach((course, index) => {
console.log(`${index + 1}. ${course}`);
});
// Output:
// 1. Web Programming
// 2. Database
// 3. Algorithms
flat() and flatMap() (ES2019)
// flat: flatten a multidimensional array
const nested = [[1, 2], [3, 4], [5, 6]];
console.log(nested.flat()); // [1, 2, 3, 4, 5, 6]
const deepNested = [[1, [2, 3]], [4, [5, [6]]]];
console.log(deepNested.flat(Infinity)); // [1, 2, 3, 4, 5, 6]
// flatMap: map + flat(1)
const sentences = ["Welcome to the campus", "Learn JavaScript"];
const words = sentences.flatMap(s => s.split(" "));
console.log(words); // ["Welcome", "to", "the", "campus", "Learn", "JavaScript"]
Case Study: Course List, Score Filtering, and Calculating Averages
// === ACADEMIC SYSTEM ===
const studentList = [
{
studentId: "2024100123",
name: "John Smith",
courses: [
{ code: "IF101", name: "Web Programming", score: 85, credits: 3 },
{ code: "IF102", name: "Database", score: 78, credits: 3 },
{ code: "IF103", name: "Algorithms", score: 92, credits: 4 }
]
},
{
studentId: "2024100124",
name: "Mike Brown",
courses: [
{ code: "IF101", name: "Web Programming", score: 70, credits: 3 },
{ code: "IF102", name: "Database", score: 65, credits: 3 },
{ code: "IF103", name: "Algorithms", score: 80, credits: 4 }
]
}
];
// 1. Calculate each student's GPA
const gpaResults = studentList.map(student => {
const totalWeight = student.courses.reduce((sum, c) => {
let weight;
if (c.score >= 85) weight = 4;
else if (c.score >= 80) weight = 3.5;
else if (c.score >= 75) weight = 3;
else if (c.score >= 70) weight = 2.5;
else weight = 2;
return sum + (weight * c.credits);
}, 0);
const totalCredits = student.courses.reduce((sum, c) => sum + c.credits, 0);
const gpa = totalWeight / totalCredits;
return {
studentId: student.studentId,
name: student.name,
gpa: Math.round(gpa * 100) / 100
};
});
console.log("=== STUDENT GPA LIST ===");
gpaResults.forEach(m => console.log(`${m.name}: ${m.gpa}`));
// 2. Filter scores >= 80
const highAchievers = gpaResults.filter(m => m.gpa >= 3.0);
console.log("\n=== HIGH ACHIEVERS ===");
highAchievers.forEach(m => console.log(`${m.name}: ${m.gpa}`));
// 3. Find a specific student
const john = studentList.find(m => m.name.includes("John"));
console.log(`\nFound: ${john?.name}`);
// 4. Sort by GPA
gpaResults.sort((a, b) => b.gpa - a.gpa);
console.log("\n=== RANKING ===");
gpaResults.forEach((m, i) => {
console.log(`${i + 1}. ${m.name} — GPA: ${m.gpa}`);
});
// 5. Total credit units for all students
const totalCreditsAll = studentList.reduce((sum, student) => {
return sum + student.courses.reduce((s, c) => s + c.credits, 0);
}, 0);
console.log(`\nTotal credits for all students: ${totalCreditsAll}`);
// 6. Class average per course
const courseCodes = ["IF101", "IF102", "IF103"];
const classAverages = courseCodes.map(code => {
const allScores = studentList.flatMap(student =>
student.courses.filter(c => c.code === code).map(c => c.score)
);
const avg = allScores.reduce((s, n) => s + n, 0) / allScores.length;
return { code, averageScore: Math.round(avg * 100) / 100 };
});
console.log("\n=== CLASS AVERAGE ===");
classAverages.forEach(c => {
console.log(`${c.code}: ${c.averageScore}`);
});
Summary
| Method | Mutating | Return | Function |
|---|---|---|---|
push() |
✅ | New length | Add to the end |
pop() |
✅ | Last element | Remove from the end |
shift() |
✅ | First element | Remove from the beginning |
unshift() |
✅ | New length | Add to the beginning |
splice() |
✅ | Removed array | Remove/add at a position |
sort() |
✅ | Sorted array | Sorting |
reverse() |
✅ | Reversed array | Reversing |
slice() |
❌ | New array | Extract a portion |
concat() |
❌ | Combined array | Joining |
includes() |
❌ | Boolean | Check for presence |
indexOf() |
❌ | Index/-1 | Find a position |
find() |
❌ | Element/undefined | Find an element |
filter() |
❌ | New array | Filtering |
map() |
❌ | New array | Transform elements |
reduce() |
❌ | Single value | Accumulating |
forEach() |
❌ | undefined | Iteration |
flat() |
❌ | New array | Flattening |