1

I will be using an input field where a person types in a value.
I create the variable that they will type in: 'Ben'.
I want the function to loop thru the nameArray and return true or false.

The script is not working and I know it is rather simple.

function validateNames() {
    var name = "Ben";
    var nameArray = ["Bill", "Barry", "Zack", "Will"];
    var arrayLength = nameArray.length;
    for (var i = 0; i < arrayLength; i++) {
        //Do something
        if (name != nameArray[i]) {
            alert((nameArray[i]) + "Name is not valid.");
            console.log("Name is not found in array.");
        } else {
            return true;
            console.log(nameArray[i]);
        }
    }
}
2
  • 1
    You can't use console.log after a return statement. Commented Mar 17, 2015 at 16:12
  • That a particular nameArray[i] is not the input doesn't mean the name is not valid, it could still be at one of the other indices? Commented Mar 17, 2015 at 16:13

4 Answers 4

2

The only way for your loop logic to know that the value is not in the array is to go through the whole array first. Your loop will be alerting on every iteration until it finds a match. It also doesn't make sense to put a console.log after a return because the former will never execute:

function validateNames() {
  var name = "Ben";
  var nameArray = ["Bill", "Barry", "Zack", "Will"];
  var arrayLength = nameArray.length;
  for (var i = 0; i < arrayLength; i++) {
    if (name === nameArray[i]) {
      console.log(nameArray[i]);
      return true;
    }
  }
  console.log("Name is not found in array.");
  return false;
}

validateNames();

Javascript arrays also provide a handy method for checking whether they contain a certain value. it's called .indexOf(), and it returns -1 when there's no match:

function validateNames() {
    var name = "Ben";
    var nameArray = ["Bill","Barry","Zack","Will"];

    return nameArray.indexOf(name) !== -1;
}  
Sign up to request clarification or add additional context in comments.

7 Comments

thanks. You clarified things. I am Not getting any output in the console using chrome dev tools. Yes, I have looked at .indexOf() which is very concise. I just wanted to do this writing out the function().
@shareyourpeace Are you actually calling the function? If you click Run code snippet above, you should see output in the console.
thanks. my rookie mistake. Yes, I forgot to call the function() at the end of the script. thanks for sticking with me. It feels good to see code work. I cannot 'vote up' because I need a reputation of 15. Your response was very clear and I am certain it will assist others.
@shareyourpeace Glad to help. And even if you can't upvote, you can accept one answer per question by clicking the checkmark next to the answer. :)
I clicked it green ! Too bad that this forum doesn't allow for us to somehow remain connected. There is an ability to search for someone but not to send them a message. Many people respond but not as clearly as you have. Again, thanks.
|
0

You could use .indexOf():

var nameArray = ["Bill","Barry","Zack","Will"];
nameArray.indexOf("Bill"); // Returns 0, Bill is found
nameArray.indexOf("Hillary"); // Returns -1, Hillary not found

So your function could look like:

function validateName(name) {
    return nameArray.indexOf(name) !== -1;
}

Please bear in mind it does not work on IE8 or below.

1 Comment

Thanks. All of the above is helpful. The answer that RLRishe provided was what I was looking for. I want to start straight-forward - with a function and 'console' output. I modified my code as RLRishe suggested. I am using 'chrome dev tools' but I am not getting anything in the Console. Why ?
0

easy fix :)

var nameArray = ["Bill", "Barry", "Zack", "Will"];

console.log(validateName("Ben", nameArrray)); // False

console.log(validateName("Will", nameArrray)); // True

function validateName(name, arr){
    var found = 0;

    for(var i = 0; i < arr.length; i++){
        found += (name === arr[i])? 1 : 0;
    }
    var result = (found>0)? true: false;

    return result;
}

1 Comment

You know, you could use Array.prototype.some instead of creating a "found" variable and returning it.
0

This will be false, because Ben does not exist in the array

if (nameArray.indexOf(name) > -1)

You can add a contains() method to the Array class so that you do not have to type this out each time.

// Static method
if (Array.contains === undefined) {
    Array.contains = function(arr, val) {
        return arr.indexOf(val) > -1;
    }
}

// Instance method
if (Array.prototype.contains === undefined) {
    Array.prototype.contains = function(val) {
        return this.indexOf(val) > -1;
    }
}

var nameArray = ["Bill", "Barry", "Zack", "Will"];
var name = "Ben";

Array.contains(nameArray, name); // false
nameArray.contains(name);        // false

You could also use some Array.prototype.some.

if (Array.prototype.contains === undefined) {
    Array.prototype.contains = function(val) {
        return this.some(function(item) {
            return item === name;
        });
    }
}

A better approach is to polyfill Array.prototype.includes(). This is an upcoming method in ECMAScript 7.

Polyfill

if (![].includes) {
  Array.prototype.includes = function(searchElement /*, fromIndex*/ ) {'use strict';
    var O = Object(this);
    var len = parseInt(O.length) || 0;
    if (len === 0) {
      return false;
    }
    var n = parseInt(arguments[1]) || 0;
    var k;
    if (n >= 0) {
      k = n;
    } else {
      k = len + n;
      if (k < 0) {k = 0;}
    }
    var currentElement;
    while (k < len) {
      currentElement = O[k];
      if (searchElement === currentElement ||
         (searchElement !== searchElement && currentElement !== currentElement)) {
        return true;
      }
      k++;
    }
    return false;
  };
}

Usage

[1, 2, 3].includes(2);     // true
[1, 2, 3].includes(4);     // false
[1, 2, 3].includes(3, 3);  // false
[1, 2, 3].includes(3, -1); // true
[1, 2, NaN].includes(NaN); // true

4 Comments

You should assign it to Array's prototype and use this instead.
You may or may not want to do this.
Array hasn't got any functions like that. All I'm saying it makes much more sense to assign it to the prototype to follow the standard design pattern.
@MMM Actually, Array.prototype.includes() was going to be called contains() until the browser makers realized that naming it so would break the web. So of all the things not to put on the Array prototype, contains is pretty high on the list.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.