Viewed   117 times

Is there a way in JavaScript to compare values from one array and see if it is in another array?

Similar to PHP's in_array function?

 Answers

4

No, it doesn't have one. For this reason most popular libraries come with one in their utility packages. Check out jQuery's inArray and Prototype's Array.indexOf for examples.

jQuery's implementation of it is as simple as you might expect:

function inArray(needle, haystack) {
    var length = haystack.length;
    for(var i = 0; i < length; i++) {
        if(haystack[i] == needle) return true;
    }
    return false;
}

If you are dealing with a sane amount of array elements the above will do the trick nicely.

EDIT: Whoops. I didn't even notice you wanted to see if an array was inside another. According to the PHP documentation this is the expected behavior of PHP's in_array:

$a = array(array('p', 'h'), array('p', 'r'), 'o');

if (in_array(array('p', 'h'), $a)) {
    echo "'ph' was foundn";
}

if (in_array(array('f', 'i'), $a)) {
    echo "'fi' was foundn";
}

if (in_array('o', $a)) {
    echo "'o' was foundn";
}

// Output:
//  'ph' was found
//  'o' was found

The code posted by Chris and Alex does not follow this behavior. Alex's is the official version of Prototype's indexOf, and Chris's is more like PHP's array_intersect. This does what you want:

function arrayCompare(a1, a2) {
    if (a1.length != a2.length) return false;
    var length = a2.length;
    for (var i = 0; i < length; i++) {
        if (a1[i] !== a2[i]) return false;
    }
    return true;
}

function inArray(needle, haystack) {
    var length = haystack.length;
    for(var i = 0; i < length; i++) {
        if(typeof haystack[i] == 'object') {
            if(arrayCompare(haystack[i], needle)) return true;
        } else {
            if(haystack[i] == needle) return true;
        }
    }
    return false;
}

And this my test of the above on it:

var a = [['p','h'],['p','r'],'o'];
if(inArray(['p','h'], a)) {
    alert('ph was found');
}
if(inArray(['f','i'], a)) {
    alert('fi was found');
}
if(inArray('o', a)) {
    alert('o was found');
}  
// Results:
//   alerts 'ph' was found
//   alerts 'o' was found

Note that I intentionally did not extend the Array prototype as it is generally a bad idea to do so.

Thursday, November 24, 2022
2

If a function is defined at the global level, then it automatically becomes a child of the window object.

Therefore you can always call window.functionName(); any place you would normally just call functionName();.

Further, since in Javascript objects work like associative arrays, you can call any child of any object using array syntax like this: object['childName']. This includes functions, so you can do object['functionName'](); for any function which is a member of an object.

Combining these two points together, you can call any globally defined function like so:

window['functionName']();

And since functionName in the above example is a string, you can use a variable in those brackets, which means you've got the same functionality as PHP's call_user_func().

[EDIT]

As I stated, this works for any object. The OP's comments state that the functions he wants to use this way are in a JQuery plug-in. They are therefore likely to be part of the JQuery object, and would normally be called like so: JQuery().functionName(); (or with the $ in place of JQuery).

Javascript syntax allows us to use ['functionName']() in any place where we can use .functionName(), so therefore, taking the above JQuery example, we could change it to look like this:

JQuery()['functionName']();`

But this technique can be adapted for any Javascript object. Any place where you use .functionName(), it can be replaced with ['functionName']().

Friday, December 9, 2022
1

Say you have a list of p tags you would like to capture the click for the p tag:

var p = document.getElementsByTagName("p"); 
for(var i=0; i<p.length; i++){ 
 p[i].onclick = function(){ 
   alert("p is clicked and the id is " + this.id); 
 } 
}

Check out an example here for more clarity: http://jsbin.com/onaci/

Wednesday, August 31, 2022
 
2

If you don't want to use javascript, you can handle it via php. Take a look at this lib: http://code.google.com/p/php-mobile-detect/. And then you could do something like:

<?php
include 'Mobile_Detect.php';
$detect = new Mobile_Detect();

if ($detect->isMobile()) {
    header('Location: yourpage.php');
    exit(0);
}
Friday, October 21, 2022
1

Cookies are not the way to transfer variables between client and server. you should append key/variables pairs to your request URL using either a get (querystring) or post method.

jQuery ajax example;

$.get('http://www.myphpserver.com/script.php?row_id=' + NewCookieValue);
Monday, October 31, 2022
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :