445,885 Members | 1,499 Online
Need help? Post your question and get tips & solutions from a community of 445,885 IT Pros & Developers. It's quick & easy.

# If value is in a list

 P: n/a I have a list of numbers, e.g., (1,3,4,5,8,16,20), and am trying to create a simple IF statement to see if the value is in that list. Is there an easier or more efficient way, than the sample code below, to do it? ===== Jun 27 '08 #1
19 Replies

 P: n/a On Apr 22, 2:43 pm, Mike num = 2; list = [1,3,4,5,8,16,20]; if(isInList( num, list )) { alert("It's there!");} else { alert("It's NOT there!"); } function isInList( num, list ) { // List is an Array() result = false; for(i in list) { if(num == list[i]) { result = true } } return result} What about alert(num in list); Jun 27 '08 #2

 P: n/a What about alert(num in list);- Hide quoted text - Yes, that would work, but I'm actually concerned about the isInList function. I imagine there's some way to avoid the whole for(i in list) routine. For example, is there a way to do this: function isInList( number, list ) { if(number == anyElementIn( list ) { return true } else { return false } } is there some built in javascript method that will check a value against any value in an Array? Thanks! Mike Jun 27 '08 #3

 P: n/a On Apr 22, 3:12 pm, Mike

 P: n/a On Apr 23, 12:12 am, Mike Benchmark
-- Peroli Sivaprakasam Jun 27 '08 #5

 P: n/a Mike wrote: >What about alert(num in list);- Hide quoted text - Yes, that would work, but I'm actually concerned about the isInList function. I imagine there's some way to avoid the whole for(i in list) routine. For example, is there a way to do this: function isInList( number, list ) { if(number == anyElementIn( list ) { return true } else { return false } } is there some built in javascript method that will check a value against any value in an Array? Thanks! Mike (','+list.toString()+',').indexOf(','+num+',') If IE had implemeneted it properly you'd only need list.indexOf(num) Jun 27 '08 #6

 P: n/a On Apr 22, 3:59*pm, "Paul Lautman" wrote: Mike wrote: What about alert(num in list);- Hide quoted text - Yes, that would work, but I'm actually concerned about the isInList function. *I imagine there's some way to avoid the whole for(i in list) routine. *For example, is there a way to do this: function isInList( number, list ) { *if(number == anyElementIn( list ) { return true } else { return false } } is there some built in javascript method that will check a value against any value in an Array? Thanks! Mike (','+list.toString()+',').indexOf(','+num+',') If IE had implemeneted it properly you'd only need list.indexOf(num)- Hidequoted text - - Show quoted text - You could also use RegExp: function isInArray(value, array) { return (new RegExp('^(' + array.join('|') + ')\$').test(value)); } Jun 27 '08 #7

 P: n/a Tom Cole wrote: On Apr 22, 3:59 pm, "Paul Lautman" wrote: >Mike wrote: >What about alert(num in list);- Hide quoted text - Yes, that would work, but I'm actually concerned about the isInList function. I imagine there's some way to avoid the whole for(i in list) routine. For example, is there a way to do this: function isInList( number, list ) { if(number == anyElementIn( list ) { return true } else { return false } } is there some built in javascript method that will check a value against any value in an Array? Thanks! Mike (','+list.toString()+',').indexOf(','+num+',')If IE had implemeneted it properly you'd only needlist.indexOf(num)- Hide quoted text -- Show quoted text - You could also use RegExp: function isInArray(value, array) { return (new RegExp('^(' + array.join('|') + ')\$').test(value)); } I could, but I am not the one asking for help, so I'm not likely to. Jun 27 '08 #8

 P: n/a Mike wrote: I have a list of numbers, e.g., (1,3,4,5,8,16,20), and am trying to create a simple IF statement to see if the value is in that list. Is there an easier or more efficient way, than the sample code below, to do it? =====

 P: n/a Mike wrote: >What about alert(num in list);- Hide quoted text - Yes, that would work, [...] No, it would not. This expression evaluates to `true' if the value of `num' is the name of a property of the object referred to by `list'. So 2 in [1, 2] evaluates to `false' even though `2' is clearly an element in `[1, 2]': [1, 2][2] or equally [1, 2]["2"] is undefined as there is no third element (with index 2). Therefore, what could work is to use the array elements as property names for an Object object, and then apply the `in' operation on the latter: var list = [1, 2]; var o = {}; for (var i = list.length; i--;) { o[list[i]] = true; } // true 2 in o Note that the `in' operation, unlike for..in iteration, requires JavaScript 1.4, JScript 5.0, ECMAScript Ed. 3. See also http://PointedEars.de/es-matrix/ Please don't remove the attribution line next time. PointedEars -- var bugRiddenCrashPronePieceOfJunk = ( navigator.userAgent.indexOf('MSIE 5') != -1 && navigator.userAgent.indexOf('Mac') != -1 ) // Plone, register_function.js:16 Jun 27 '08 #10

 P: n/a Paul Lautman wrote: Mike wrote: >[...] For example, is there a way to do this:function isInList( number, list ) { if(number == anyElementIn( list ) { return true } else { returnfalse }}is there some built in javascript method that will check a valueagainst any value in an Array?[...] (','+list.toString()+',').indexOf(','+num+',') Good idea, but this really only works for arrays that have serializable values as elements. One can implement general serialization by overwriting Object.prototype.toString() (without breaking for..in iteration), but only enumerable properties and non-enumerable properties of which the names are known can be included. If IE had implemeneted it properly you'd only need list.indexOf(num) Array.prototype.indexOf() is a proprietary JavaScript 1.6+ feature not specified in ECMAScript, so it is pointless to say that IE did not implement it properly. It is even more pointless because it would not have to be IE/MSHTML but Microsoft JScript to implement it. Please trim your quotes, especially don't quote signatures. PointedEars -- var bugRiddenCrashPronePieceOfJunk = ( navigator.userAgent.indexOf('MSIE 5') != -1 && navigator.userAgent.indexOf('Mac') != -1 ) // Plone, register_function.js:16 Jun 27 '08 #11

 P: n/a Paul Lautman wrote: (','+list.toString()+',').indexOf(','+num+',') BTW, (',' + list + ',').indexOf(',' + num + ',') suffices as string concatenation implicitly calls String.prototype.toString() on its non-string operands. PointedEars -- Prototype.js was written by people who don't know javascript for people who don't know javascript. People who don't know javascript are not the best source of advice on designing systems that use javascript. -- Richard Cornford, cljs, Jun 27 '08 #12

 P: n/a On Apr 22, 8:39 pm, Thomas 'PointedEars' Lahn wrote: Paul Lautman wrote: (','+list.toString()+',').indexOf(','+num+',') BTW, (',' + list + ',').indexOf(',' + num + ',') suffices as string concatenation implicitly calls String.prototype.toString() on its non-string operands. PointedEars -- Prototype.js was written by people who don't know javascript for people who don't know javascript. People who don't know javascript are not the best source of advice on designing systems that use javascript. -- Richard Cornford, cljs, People... lest use the things for the ends that they was created! What's the problem using for?! Usign RegExp... you'll need to turn the list into a string... it's an unnecessary step. function arrayMember (value,list) { for (var i in list) if (list[i]===value) return i; break; }; return false; } This is good for biiiiiiigger lists, once it break! :D And you will have what can be a useful info: the index! --- About prototype, scriptaculous, jquery, etc... I don't like to use them... I prefer do little specific libs and put on my code when necessary... I dislike to use excessive object abbreviations... but, I think, even with these I can learn something. That's the spirit! Jun 27 '08 #13

 P: n/a On Apr 22, 10:47 pm, Thadeu de Paula wrote: Paul Lautman wrote: (','+list.toString()+',').indexOf(','+num+',') BTW, (',' + list + ',').indexOf(',' + num + ',') suffices as string concatenation implicitly calls String.prototype.toString() on its non-string operands. PointedEars -- Prototype.js was written by people who don't know javascript for people who don't know javascript. People who don't know javascript are not the best source of advice on designing systems that use javascript. -- Richard Cornford, cljs, People... lest use the things for the ends that they was created! What's the problem using for?! Usign RegExp... you'll need to turn the list into a string... it's an unnecessary step. function arrayMember (value,list) { for (var i in list) if (list[i]===value) return i; break; }; return false; } This is good for biiiiiiigger lists, once it break! :D And you will have what can be a useful info: the index! --- About prototype, scriptaculous, jquery, etc... I don't like to use them... I prefer do little specific libs and put on my code when necessary... I dislike to use excessive object abbreviations... but, I think, even with these I can learn something. That's the spirit! Oppps... there something wrong.. sorry! function arrayMember (value,list) { for (var i in list) if (list[i]===value) { return i; break; }; return false; }; Jun 27 '08 #14

 P: n/a Thadeu de Paula wrote: function arrayMember (value,list) { for (var i in list) if (list[i]===value) { return i; break; }; return false; }; This is error-prone for the reasons I gave in Please trim your quotes, see http://jibbering.com/faq/ pp. PointedEars -- Prototype.js was written by people who don't know javascript for people who don't know javascript. People who don't know javascript are not the best source of advice on designing systems that use javascript. -- Richard Cornford, cljs, Jun 27 '08 #15

 P: n/a Thomas 'PointedEars' Lahn wrote: Thadeu de Paula wrote: >function arrayMember (value,list) { for (var i in list) if (list[i]===value) { return i; break; }; return false;}; This is error-prone for the reasons I gave in Sorry, I meant . PointedEars Jun 27 '08 #16

 P: n/a In comp.lang.javascript message <074fe8ad-e977-4925-9aef-8926efc78b31@8g 2000hse.googlegroups.com>, Tue, 22 Apr 2008 11:43:14, Mike I have a list of numbers, e.g., (1,3,4,5,8,16,20), and am trying tocreate a simple IF statement to see if the value is in that list. Isthere an easier or more efficient way, than the sample code below, todo it? Yes, undoubtedly. If the list is unordered, a full scan is unavoidable; it should be (assuming the list is in an Array) scanned with a while loop scanning down only until the value is found. If the list is ordered, I guess that a binary chop search **might** be more efficient, depending on the JavaScript implementation. If the list is to be searched many times, and is not too sparse, it could well be worth inverting it with, say, A = [] ; J = L.length ; while (J--) A[L[J]] = 1 since your test for value V then becomes just if (A[V]) and the internal code for that ought to be efficient. Test it. Results may depend on how sparse the original list is, as well as how long; there could be a considerable difference in speed between the lists (0, 3, 6, 9) and (0, 3e3, 6e6, 9e9). If the list is a String of separated numbers, then use IndexOf or a RegExp, remembering that the search must, unless the numbers are padded to constant length, seek also the separators. If the search is to be done many times, sort the entries, split the string, and look only in the right part - when seeking information on Gnus in a large encyclopaedia, one first selects the volumes containing the G-words, and does not read about Aardvarks or Eels or Oxen /en route/. It's a good idea to read the newsgroup c.l.j and its FAQ. See below. -- (c) John Stockton, nr London UK. ?@merlyn.demon.co.uk IE7 FF2 Op9 Sf3 news:comp.lang.javascript FAQ .

 P: n/a On Apr 23, 1:47*pm, Dr J R Stockton , Tue, 22 Apr 2008 11:43:14, Mike . *