Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Joining a JavaScript array with a condition?
Joining a JavaScript array with a condition involves filtering elements that meet specific criteria and then combining them into a string. This is achieved by chaining the filter() method with the join() method.
Syntax
array.filter(condition).join(separator)
Parameters
- condition - A function that tests each element
- separator - String used to separate elements (default is comma)
Example: Joining Even Numbers
Document Click the above button to join the array elements that are divisible by 2.
Method 1: Using filter() and join()
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 11, 22, 33, 18];
console.log("Original array:", numbers);
// Join even numbers with " : "
let evenNumbers = numbers.filter(num => num % 2 === 0).join(" : ");
console.log("Even numbers joined:", evenNumbers);
Original array: [1, 2, 3, 4, 5, 6, 7, 8, 11, 22, 33, 18] Even numbers joined: 2 : 4 : 6 : 8 : 22 : 18
Method 2: Multiple Conditions
let scores = [45, 78, 92, 33, 88, 67, 95, 42];
console.log("Original scores:", scores);
// Join passing grades (>= 60) with comma
let passingGrades = scores.filter(score => score >= 60).join(", ");
console.log("Passing grades:", passingGrades);
// Join excellent grades (>= 90) with " | "
let excellentGrades = scores.filter(score => score >= 90).join(" | ");
console.log("Excellent grades:", excellentGrades);
Original scores: [45, 78, 92, 33, 88, 67, 95, 42] Passing grades: 78, 92, 88, 67, 95 Excellent grades: 92 | 95
Method 3: String Conditions
let fruits = ["apple", "banana", "cherry", "date", "elderberry"];
console.log("Original fruits:", fruits);
// Join fruits with more than 5 characters
let longFruits = fruits.filter(fruit => fruit.length > 5).join(" - ");
console.log("Long fruit names:", longFruits);
// Join fruits starting with 'b' or 'c'
let selectedFruits = fruits.filter(fruit => fruit.startsWith('b') || fruit.startsWith('c')).join(" & ");
console.log("Fruits starting with b or c:", selectedFruits);
Original fruits: [apple, banana, cherry, date, elderberry] Long fruit names: banana - cherry - elderberry Fruits starting with b or c: banana & cherry
Comparison
| Method | Use Case | Performance |
|---|---|---|
| filter().join() | Simple conditions | Good |
| Multiple filter().join() | Different criteria | Good |
| Complex conditions | Advanced filtering | Depends on condition |
Conclusion
Combining filter() and join() provides a clean way to conditionally join array elements. This pattern is efficient and readable for most filtering scenarios.
Advertisements
