Enumerating array elements without cycles

29.04.19

The examples are very abstract, since the cycles exist. You must select all the elements of the array for a given attribute. There are several solutions.

The most appropriate option in PHP is to use the built-in function array_filter(). Imagine that it does not exist either. We write our using recursion.

On PHP, the function looks like this:

function getArrayElements($arr, $pattern) {
    static $i = 0;
    static $arrayResult = array();
    if (preg_match($pattern, $arr[$i])) {
        $arrayResult[] = $arr[$i];
    }
    $i++;
    if (count($arr) == $i) {
        return;
    } else {
        getArrayElements($arr, $pattern);
    }
    return $arrayResult;
}

Example:

$arr = array('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

var 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:

var arr = ['a', 'xd', 'w', 1, 'y', 'x'],
    pattern = /^x/;
console.log(getArrayElements(arr, pattern)); //["xd", "x"]
blog comments powered by Disqus