0

I'm trying to find if a value exists or not in an array and then add it to a third array. I am using JavaScript.

Here are my declarations:

var testArray1 = ["a", "b", "c", "d", "e"];
var testArray2 = [];

Here is my code snippet:

var x = testArray1.length;
var y = 0;

do {
    if(typeof testArray1[y] == 'a') {
    console.value += "A doesn't exist.";
    }
    else {
    console.value += "A does exist."
    }
    y++;
while (y < x);

For some reason (even if I enter in (anything greater than 0) instead of x it always says A does exist. Could anyone point me out where my code is wrong?

Thanks!

The Man
  • 89
  • 1
  • 10
  • 3
    `typeof` **never** returns `'a'`. What do you think `typeof` does? How/why do you conclude from the equality to `"a"` that the value does exist? – Felix Kling Jan 28 '15 at 03:02
  • 1
    See [Best way to find an item in a JavaScript array?](http://stackoverflow.com/q/143847/218196) for a solution to test existence of an element in an array. – Felix Kling Jan 28 '15 at 03:06
  • Notice that your solution will not work for empty arrays. Don't use a `do-while`-loop here – Bergi Jan 28 '15 at 03:13

3 Answers3

1

Why doesn't my code work for finding if a value exists in an array in JavaScript?

Because typeof x returns the type of the value (according to the specification). typeof testArray1[y] will always return "string" for every value in your array, because every value is a string. It will never return 'a'.

Have a look at Best way to find if an item is in a JavaScript array? and How do I check if an array includes an object in JavaScript? to learn how to test for existence of a value in an array.

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
0

You can make this way simpler for yourself.

testArray1.indexOf('a') will return the index of that letter in the array. If it's not in the array it will return -1

if(testArray1.indexOf('a') != -1){
     // it is in the array
}else{
     // it's not in the array
}
Kolby
  • 2,775
  • 3
  • 25
  • 44
  • Thanks for the clear and, _quite frankly_, easy answer! That simplifies my code quite a bit! – The Man Jan 28 '15 at 03:18
  • @TheMan: For future questions, I recommend to ask *exactly* what you want. You currently ask for an explanation why your code does not work, not how to correctly test for existence (which would be a duplicate anyway). – Felix Kling Jan 28 '15 at 03:32
0

For me, I would approach solving the problem like this.

var _testArray1 = ["a", "b", "c", "d", "e"];
var _testArray2 = [];

for (var _i = 0; _i < _testArray1.length; _i++) {
    if (_testArray1[_i] === "a") {
        _testArray2.push(_testArray1[_i]);
    }
    // other logic;
};

In this way, you keep your iteration count variable within its own scope, as well as append the found array result to the already declared variable.

lindsay
  • 972
  • 2
  • 11
  • 21