Wrox Programmer Forums
|
Javascript General Javascript discussions.
Welcome to the p2p.wrox.com Forums.

You are currently viewing the Javascript section of the Wrox Programmer to Programmer discussions. This is a community of software programmers and website developers including Wrox book authors and readers. New member registration was closed in 2019. New posts were shut off and the site was archived into this static format as of October 1, 2020. If you require technical support for a Wrox book please contact http://hub.wiley.com
 
Old January 26th, 2006, 12:51 PM
Authorized User
 
Join Date: Sep 2004
Posts: 36
Thanks: 0
Thanked 0 Times in 0 Posts
Default Comparing Arrays

Hi,

 I have two arrays, could anybody tell me how I can loop through them and see if a value appears in both?

Thankyou

 
Old January 26th, 2006, 01:24 PM
richard.york's Avatar
Wrox Author
 
Join Date: Jun 2003
Posts: 1,706
Thanks: 0
Thanked 6 Times in 6 Posts
Default

This replicates in JavaScript the PHP function in_array().

Code:
function in_array($needle, $haystack)
{
    for (var $i in $haystack)
    {
         if ($haystack[$i] == $needle)
         {
              return true;
         }
    }
    return false;
}

See if a value appears in both:

Code:
for (var $i in $array1)
{
    if (in_array($array1[$i], $array2))
    {
         alert('value: ' + $array[$i] + ' appears in both $array1 and $array2');
    }
}
HTH!

Regards,
Rich

--
[http://www.smilingsouls.net]
Mail_IMAP: A PHP/C-Client/PEAR solution for webmail
Author: Beginning CSS: Cascading Style Sheets For Web Design
 
Old January 27th, 2006, 05:48 AM
Authorized User
 
Join Date: Sep 2004
Posts: 36
Thanks: 0
Thanked 0 Times in 0 Posts
Default

Hi,

Thanks for that.

I'm not sure how to modify that to fit in with my array's.

Here are my two array's:



Code:
var list1 = "1,2,3,5";
var valueArray1 = new Array();
valueArray1 = list1.split(',');

var list2 = "5,6,7,8";
var valueArray2 = new Array();
valueArray2 = list2.split(',');
Could you tell me where they go in your script?

Thanks for your time






Similar Threads
Thread Thread Starter Forum Replies Last Post
Comparing dates Tomi XSLT 1 September 21st, 2006 04:45 AM
Comparing Files... Nick Y BOOK: Ivor Horton's Beginning Visual C++ 2005 0 July 30th, 2006 02:48 PM
Multidemmesional Arrays OR arrays gmoney060 Classic ASP Basics 3 November 1st, 2004 03:42 PM
Comparing arrays in javascript JohnD Javascript How-To 0 August 29th, 2004 02:32 PM





Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
Copyright (c) 2020 John Wiley & Sons, Inc.