Iterating Elements of Array without Loops
Last updated: 27.08.2025
Views: 489
The examples are very abstract because there are cycles. Our condition will be as follows. It is necessary to select all elements of the array by a given attribute. Or, to put it more precisely, it is necessary to filter the array. There are several solutions.
The most suitable option in PHP is to use the built-in function array_filter(). Let’s imagine that it does not exist either. We write it using recursion.
On PHP, the function looks like this:
PHP
function getArrayElements($arr, $pattern) {
static $i = 0;
static $arrayResult = [];
if (preg_match($pattern, $arr[$i])) {
$arrayResult[] = $arr[$i];
}
$i++;
if (count($arr) == $i) {
return;
} else {
getArrayElements($arr, $pattern);
}
return $arrayResult;
}
Example:
PHP
$arr = ['a', 'xd', 'w', 1, 'y', 'x']; $pattern = '/^x/'; print_r(getArrayElements($arr, $pattern)); // Array ( [0] => xd [1] => x )
Now let’s look at the same thing in JavaScript. In JS, an array has a similar filter() method. Let’s try to do without it, use recursion
JavaScript
let i = 0,
arrayResult = [];
function getArrayElements(arr, pattern) {
if (pattern.test(arr[i])) {
arrayResult.push(arr[i]);
}
i++;
if (arr.length == i) {
return;
} else {
getArrayElements(arr, pattern);
}
return arrayResult;
}
Example:
JavaScript
const arr = ['a', 'xd', 'w', 1, 'y', 'x'],
pattern = /^x/;
console.log(getArrayElements(arr, pattern)); //["xd", "x"]
Similar posts:
-
How to Get Max Value in JavaScript Array
A short note about finding the maximum value in a JavaScript array with numeric values. The Array object in JS does not have its own max method. To find the maximum va...
-
Smooth Scrolling to Anchor Using JavaScript
Smooth scrolling is a popular web design feature that enhances user experience by allowing seamless navigation between sections of a webpage. Instead of abrupt jumps, smo...
-
Vue Accordion Component
A simple and lightweight Vue 3 accordion component plugin. Supports both global plugin registration and local component usage. Written in TypeScript. The accordion compon...
Leave a Reply