Search code examples
javascriptjquerylogicbusiness-logic

array_search Recursive in javascript


function array_searchRecursive( $needle, $haystack, $strict=false, $path=array() )
{
    if( !is_array($haystack) ) {
        return false;
    }

    foreach( $haystack as $key => $val ) {

        if( is_array($val) && $subPath = array_searchRecursive($needle, $val, $strict, $path) ) {
            $path = array_merge($path, array($key), $subPath);

            return $path;
        } else if( (!$strict && $val == $needle) || ($strict && $val === $needle) ) {

            $path[] = $key;
            return $path;
        }
    }
    return false;
}

Do any body suggest me the same funcitonality, that can be implemented in javascript. reference http://www.php.net/manual/en/function.array-search.php#68424


Solution

  • This might give you a start. Not thoroughly tested or highly optimized, and assumes use of jQuery (shouldn't be a big problem to replace the jQuery utilty functions with other implementations).

    function searchArrayRecursive(needle, haystack, strict) {
    
        function constructPath(needle, haystack, path, strict) {
            if (!$.isArray(haystack)) {
                return false;
            }
            var index;
            for (index = 0; index < haystack.length; index++) {
                var value = haystack[index];
                var currentPath = $.merge([], path);
                currentPath.push(index);
    
                if ((strict && value === needle) || (!strict && value == needle)) {
                    return currentPath;
                }
                if ($.isArray(value)) {
    
                    var foundPath = constructPath(needle, value, currentPath, strict);
                    if (foundPath) {
                        return foundPath;
                    }
                }
            }
    
            return false;
        }
    
    
        return constructPath(needle, haystack, [], strict);
    }
    

    http://jsfiddle.net/b8TxJ/2/