Comparing Filter, Map, and Find in Swift and JavaScrip
In this blog post, we'll explore how to use three fundamental array methods, filter, map, and find, in both Swift and JavaScript. We'll compare the shorthand notation ($0, $1, etc.) used in Swift with the named parameter notation for increased clarity and readability.
Filter in Swift:
let numbers = [1, 2, 3, 4, 5]
// Using $0 shorthand notation
let evenNumbers = numbers.filter { $0 % 2 == 0 }
// Output: [2, 4]
// Using named parameter notation
let oddNumbers = numbers.filter { number in
return number % 2 != 0
}
// Output: [1, 3, 5]
Filter in JavaScript:
const numbers = [1, 2, 3, 4, 5];
// Using anonymous function
const evenNumbers = numbers.filter(num => num % 2 === 0);
// Output: [2, 4]
// Using named function
const oddNumbers = numbers.filter(function(num) {
return num % 2 !== 0;
});
// Output: [1, 3, 5]
Map in Swift:
let numbers = [1, 2, 3, 4, 5]
// Using $0 shorthand notation
let squaredNumbers = numbers.map { $0 * $0 }
// Output: [1, 4, 9, 16, 25]
// Using named parameter notation
let doubledNumbers = numbers.map { number in
return number * 2
}
// Output: [2, 4, 6, 8, 10]
Map in Javascript:
const numbers = [1, 2, 3, 4, 5];
// Using arrow function
const squaredNumbers = numbers.map(num => num * num);
// Output: [1, 4, 9, 16, 25]
// Using named function
const doubledNumbers = numbers.map(function(num) {
return num * 2;
});
// Output: [2, 4, 6, 8, 10]
Find in Swift:
let numbers = [1, 2, 3, 4, 5]
// Using $0 shorthand notation
if let foundNumber = numbers.first(where: { $0 == 3 }) {
print("Found number: \(foundNumber)")
} else {
print("Number not found")
}
// Output: Found number: 3
// Using named parameter notation
if let foundNumber = numbers.first(where: { number in
return number == 3
}) {
print("Found number: \(foundNumber)")
} else {
print("Number not found")
}
// Output: Found number: 3
Find in Javascript:
const numbers = [1, 2, 3, 4, 5];
// Using arrow function
const foundNumber = numbers.find(num => num === 3);
console.log(foundNumber !== undefined ? `Found number: ${foundNumber}` : "Number not found");
// Output: Found number: 3
// Using named function
const foundNumber2 = numbers.find(function(num) {
return num === 3;
});
console.log(foundNumber2 !== undefined ? `Found number: ${foundNumber2}` : "Number not found");
// Output: Found number: 3

Comments
Post a Comment