If value is in a list

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Mike

    If value is in a list

    I have a list of numbers, e.g., (1,3,4,5,8,16,2 0), 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?

    =====

    <script type="text/javascript">
    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
    }
    </script>
  • Tom Cole

    #2
    Re: If value is in a list

    On Apr 22, 2:43 pm, Mike <mpea...@gmail. comwrote:
    I have a list of numbers, e.g., (1,3,4,5,8,16,2 0), 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?
    >
    =====
    >
    <script type="text/javascript">
    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}
    >
    </script>
    What about alert(num in list);

    Comment

    • Mike

      #3
      Re: If value is in a list

      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

      Comment

      • Tom Cole

        #4
        Re: If value is in a list

        On Apr 22, 3:12 pm, Mike <mpea...@gmail. comwrote:
        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
        I've looked around as I'm not aware of one. The best I can come up
        with is:

        function doCheck(value, array) {
        for (var i = 0; i < array.length; i++) {
        if (array[i] == value) {
        return true;
        }
        }
        return false;
        }

        This method returns immediately upon a success, rather than looping
        through the entire array every time as your first example did.

        Comment

        • Peroli

          #5
          Re: If value is in a list

          On Apr 23, 12:12 am, Mike <mpea...@gmail. comwrote:
          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
          Mike,
          You can use "indexOf" (Javascript 1.6, so won't work in IE) method
          on an array instead. But its performance differs from browser to
          browser.
          "num in list" is faster in Firefox, but slower in Safari.


          --- script ---

          <html>
          <head>
          <title>Benchmar k</title>
          </head>
          <body>
          <form id="test_form" >
          <input type="button" value="Benchmar k" onclick="benchm ark()">
          </form>
          <span id="result" />
          <script type="text/javascript">
          function benchmark() {
          var a = [1,3,4,5,8,16,20];
          var d = new Date();
          for(var i=0; i<100000; i++) {
          var a1 = a.indexOf(8);
          }
          var t1 = (new Date()) - d;
          d = new Date();
          for(var i=0; i<100000; i++) {
          var a1 = 8 in a;
          }
          var t2 = (new Date()) - d;
          document.getEle mentById('resul t').innerHTML = "indexOf:" + t1 +
          '<br />in:' + t2;
          }
          </script>
          </body>
          </html>

          -- Peroli Sivaprakasam

          Comment

          • Paul Lautman

            #6
            Re: If value is in a list

            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.toStr ing()+',').inde xOf(','+num+',' )

            If IE had implemeneted it properly you'd only need list.indexOf(nu m)


            Comment

            • Tom Cole

              #7
              Re: If value is in a list

              On Apr 22, 3:59 pm, "Paul Lautman" <paul.laut...@b tinternet.com>
              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.toStr ing()+',').inde xOf(','+num+',' )
              >
              If IE had implemeneted it properly you'd only need list.indexOf(nu m)- Hidequoted text -
              >
              - Show quoted text -
              You could also use RegExp:

              function isInArray(value , array) {
              return (new RegExp('^(' + array.join('|') + ')$').test(valu e));
              }

              Comment

              • Paul Lautman

                #8
                Re: If value is in a list

                Tom Cole wrote:
                On Apr 22, 3:59 pm, "Paul Lautman" <paul.laut...@b tinternet.com>
                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.toSt ring()+',').ind exOf(','+num+', ')
                >>
                >If IE had implemeneted it properly you'd only need
                >list.indexOf(n um)- Hide quoted text -
                >>
                >- Show quoted text -
                >
                You could also use RegExp:
                >
                function isInArray(value , array) {
                return (new RegExp('^(' + array.join('|') + ')$').test(valu e));
                }
                I could, but I am not the one asking for help, so I'm not likely to.


                Comment

                • Thomas 'PointedEars' Lahn

                  #9
                  Re: If value is in a list

                  Mike wrote:
                  I have a list of numbers, e.g., (1,3,4,5,8,16,2 0), 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?
                  >
                  =====
                  >
                  <script type="text/javascript">
                  num = 2;
                  list = [1,3,4,5,8,16,20];
                  You should declare all your identifiers. For those which should be
                  variables, e.g.

                  var num = 2;
                  if(isInList( num, list )) {
                  alert("It's there!");
                  } else {
                  alert("It's NOT there!");
                  }
                  >
                  function isInList( num, list ) {
                  // List is an Array()
                  result = false;
                  There. You create a *globally* available property, if that. Bad.
                  for(i in list) {
                  if(num == list[i]) { result = true }
                  }
                  return result
                  }
                  This would work for numeric values, but it would be inefficient, and
                  error-prone. Note a) that you can stop looping once you have found an item,
                  b) that `==' performs implicit type conversion, and c) that for..in
                  iteration is not equivalent to C-style `for' iteration (it iterates over the
                  list of all enumerable properties, not just those designating
                  array/collection elements). Use instead

                  /**
                  * @param number num
                  * @param Array list
                  */
                  function inArray(num, list)
                  {
                  var result = false;

                  for (var i = list.length; i--;)
                  {
                  if (list[i] === num)
                  {
                  result = true;
                  break;
                  }
                  }

                  return result;
                  }

                  JavaScript 1.6+ also supports a native method:

                  list.indexOf(nu m) >= 0

                  The indexOf() method of Array instances returns the first index at which a given element can be found in the array, or -1 if it is not present.



                  PoinedEars

                  Comment

                  • Thomas 'PointedEars' Lahn

                    #10
                    Re: If value is in a list

                    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 bugRiddenCrashP ronePieceOfJunk = (
                    navigator.userA gent.indexOf('M SIE 5') != -1
                    && navigator.userA gent.indexOf('M ac') != -1
                    ) // Plone, register_functi on.js:16

                    Comment

                    • Thomas 'PointedEars' Lahn

                      #11
                      Re: If value is in a list

                      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 { return
                      >false }
                      >}
                      >>
                      >is there some built in javascript method that will check a value
                      >against any value in an Array?
                      >[...]
                      >
                      (','+list.toStr ing()+',').inde xOf(','+num+',' )
                      Good idea, but this really only works for arrays that have serializable
                      values as elements. One can implement general serialization by overwriting
                      Object.prototyp e.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(nu m)
                      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 bugRiddenCrashP ronePieceOfJunk = (
                      navigator.userA gent.indexOf('M SIE 5') != -1
                      && navigator.userA gent.indexOf('M ac') != -1
                      ) // Plone, register_functi on.js:16

                      Comment

                      • Thomas 'PointedEars' Lahn

                        #12
                        Re: If value is in a list

                        Paul Lautman wrote:
                        (','+list.toStr ing()+',').inde xOf(','+num+',' )
                        BTW,

                        (',' + list + ',').indexOf(', ' + num + ',')

                        suffices as string concatenation implicitly calls
                        String.prototyp e.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, <f806at$ail$1$8 300dec7@news.de mon.co.uk>

                        Comment

                        • Thadeu de Paula

                          #13
                          Re: If value is in a list

                          On Apr 22, 8:39 pm, Thomas 'PointedEars' Lahn <PointedE...@we b.de>
                          wrote:
                          Paul Lautman wrote:
                          (','+list.toStr ing()+',').inde xOf(','+num+',' )
                          >
                          BTW,
                          >
                          (',' + list + ',').indexOf(', ' + num + ',')
                          >
                          suffices as string concatenation implicitly calls
                          String.prototyp e.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, <f806at$ail$1$8 300d...@news.de mon.co.uk>
                          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!

                          Comment

                          • Thadeu de Paula

                            #14
                            Re: If value is in a list

                            On Apr 22, 10:47 pm, Thadeu de Paula <thadeudepa...@ gmail.comwrote:
                            On Apr 22, 8:39 pm, Thomas 'PointedEars' Lahn <PointedE...@we b.de>
                            wrote:
                            >
                            >
                            >
                            Paul Lautman wrote:
                            (','+list.toStr ing()+',').inde xOf(','+num+',' )
                            >
                            BTW,
                            >
                            (',' + list + ',').indexOf(', ' + num + ',')
                            >
                            suffices as string concatenation implicitly calls
                            String.prototyp e.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, <f806at$ail$1$8 300d...@news.de mon.co.uk>
                            >
                            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;
                            };

                            Comment

                            • Thomas 'PointedEars' Lahn

                              #15
                              Re: If value is in a list

                              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
                              <news:480E665B. 6050506@Pointed Ears.de>

                              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, <f806at$ail$1$8 300dec7@news.de mon.co.uk>

                              Comment

                              Working...