Overview
When you need to extract specific data from an array—such as characters at level 50 or above, or students with a passing score—the filter method is the best tool. It is much simpler than using for or if statements. This method creates a new array without changing the original one, which helps you write safe and clean code. In this article, we will use an example of selecting guild members by their level.
Specifications (Input/Output)
filter Method
This method runs a test function on every element in an array. It returns a new array containing only the elements that pass the test (where the result is true).
| Argument / Return | Description |
| callbackFn | The function that tests each element: (element, index, array) => boolean |
| Return Value | A new array of elements that passed the test. If nothing passes, it returns an empty array []. |
- Input: The original array.
- Output: A new array with selected elements.
- Feature: The original array is not modified.
Basic Usage
1. Filtering Numbers
You can write this in one line using an arrow function.
const scores = [45, 90, 30, 85, 60];
// Extract only scores of 80 or higher
const highScores = scores.filter(score => score >= 80);
console.log(highScores); // [90, 85]
2. Using Code Blocks (Return Required)
If you need multiple lines of code, wrap the logic in {} and use the return keyword.
const numbers = [1, 2, 3, 4, 5, 6];
const oddNumbers = numbers.filter(num => {
// Check if the number is odd
return num % 2 !== 0;
});
console.log(oddNumbers); // [1, 3, 5]
Full Code (HTML / JavaScript)
This tool allows you to select guild members who meet a minimum level requirement with a single click.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Guild Member Selector</title>
<style>
.guild-panel {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
max-width: 500px;
padding: 20px;
border: 2px solid #4a3b2c;
border-radius: 8px;
background-color: #fdf5e6;
color: #4a3b2c;
}
h3 { margin-top: 0; text-align: center; border-bottom: 2px solid #daa520; padding-bottom: 10px; }
.mission-controls {
display: flex;
justify-content: center;
gap: 10px;
margin-bottom: 20px;
}
.rank-btn {
padding: 10px 15px;
border: 1px solid #8b4513;
background-color: #fff8dc;
color: #8b4513;
border-radius: 4px;
cursor: pointer;
font-weight: bold;
transition: all 0.2s;
}
.rank-btn:hover, .rank-btn.active {
background-color: #8b4513;
color: #fff;
}
.member-list {
list-style: none;
padding: 0;
margin: 0;
border-top: 1px solid #ccc;
}
.member-card {
padding: 10px;
border-bottom: 1px dashed #ccc;
display: flex;
justify-content: space-between;
align-items: center;
}
.level-badge {
background-color: #daa520;
color: white;
padding: 3px 8px;
border-radius: 12px;
font-size: 0.9em;
}
</style>
</head>
<body>
<div class="guild-panel">
<h3>Guild Member Selection</h3>
<div class="mission-controls">
<button class="rank-btn active" data-min-level="1">All</button>
<button class="rank-btn" data-min-level="30">Mid (Lv30+)</button>
<button class="rank-btn" data-min-level="50">High (Lv50+)</button>
<button class="rank-btn" data-min-level="80">Elite (Lv80+)</button>
</div>
<ul id="party-list" class="member-list">
</ul>
<p id="party-count" style="text-align: right; font-size: 0.9em; margin-top: 10px;"></p>
</div>
<script src="guild_selector.js"></script>
</body>
</html>
JavaScript
/**
* Guild Member Selection Script
* Level-based filtering using the filter method
*/
// 1. Guild Member List
const guildMembers = [
{ name: "Mori", level: 85 },
{ name: "Kobayashi", level: 12 },
{ name: "Oki", level: 45 },
{ name: "Nakabayashi", level: 60 },
{ name: "Komori", level: 92 },
{ name: "Hayashi", level: 25 },
{ name: "Omori", level: 55 },
{ name: "Nakagi", level: 78 },
{ name: "Kogi", level: 8 },
{ name: "Obayashi", level: 33 }
];
const listContainer = document.getElementById('party-list');
const countDisplay = document.getElementById('party-count');
const buttons = document.querySelectorAll('.rank-btn');
/**
* Function to render the list
* @param {Array} members
*/
const renderMembers = (members) => {
listContainer.innerHTML = '';
if (members.length === 0) {
listContainer.innerHTML = '<li class="member-card">No members meet the requirements.</li>';
countDisplay.textContent = 'Available: 0';
return;
}
members.forEach((member) => {
const li = document.createElement('li');
li.className = 'member-card';
li.innerHTML = `
<span class="member-name">${member.name}</span>
<span class="level-badge">Lv.${member.level}</span>
`;
listContainer.appendChild(li);
});
countDisplay.textContent = `Available: ${members.length}`;
};
/**
* Filtering Execution Function
*/
const filterByLevel = (event) => {
const clickedBtn = event.target;
// Update button styles
buttons.forEach(btn => btn.classList.remove('active'));
clickedBtn.classList.add('active');
// Get the required level from data attributes
const requiredLevel = Number(clickedBtn.dataset.minLevel);
// Filter members who meet the level requirement
const selectedMembers = guildMembers.filter((member) => {
return member.level >= requiredLevel;
});
renderMembers(selectedMembers);
};
// Initial display (All members)
renderMembers(guildMembers);
// Event listeners
buttons.forEach((btn) => {
btn.addEventListener('click', filterByLevel);
});
Custom Points
To extract data within a range, such as “Level 30 or higher but less than 50,” you can extend the condition like this: list.filter(member => member.level >= 30 && member.level < 50);. If you want to exclude a specific member, use the !== operator: list.filter(member => member.name !== 'Mori');.
Cautions
Unlike the find method, filter returns an empty array [] if no elements match the condition. It does not return undefined. Always check result.length to see if any data was found. Also, remember that filter is non-destructive and does not change the original array. You must save the result in a new variable.
Advanced Usage
Cleaning Data
You can use filter to remove null, undefined, or invalid data from an array.
const rawData = [100, null, 200, undefined, 0, 300];
// Keep only values that are not null or undefined
const validData = rawData.filter(val => val != null);
console.log(validData); // [100, 200, 0, 300]
Summary
The filter method is a powerful way to sift through large amounts of data. Use it to collect all matching data or to create a new array with specific items removed. Because it leaves the original data unchanged, it is a very safe way to handle your data in JavaScript.
