1

I have two arrays of integers a=[1,3,5,7] and b=[2,4,6,8]. Now I need to check if a given var $v is in a and if it is, return the equivalent element from b. Example:

if $v in a (and $x is its position) return $b[$x].

How do I perform this?

6 Answers 6

7

the indexOf method will return the index of the array where the item was found, or -1 if it wasn't found.

var i = a.indexOf(v);
if (i != -1)
{
    return b[i]
}

EDIT: This will add the method if your browser doesn't have it.

if (!Array.prototype.indexOf)
{
    Array.prototype.indexOf = function(x)
    {
        var i;
        for (i = 0; i < this.length; i++)
        {
            if (this[i] === x)
            {
                return i;
            }
        }
        return -1;
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Note: The Array.IndexOf method is not available in IE 8 or earlier.
Rats. Edited the answer to add the method if it isn't there.
3

Loop through the items in the array:

for (var i = 0; i < a.length; i++) {
  if (a[i] == v) {
    return b[i];
  }
}
return -1; // not found

Comments

1
var i = a.indexOf(v);
if (i !== -1)
{
    return b[i]
}

1 Comment

Note: The Array.indexOf method is not available in IE 8 or earlier.
1
if(a.indexOf(v) > -1) {
  var id = a.indexOf(v);
  console.log(b[id]);
}

See for compatibility of Array.indexOf

1 Comment

Note: The Array.IndexOf method is not available in IE 8 or earlier.
0

I suppose this would work.

>> function test(k){ return b[a.indexOf(k)]}

>> test(1)
2

>> test(9)
undefined

In js, indexOf always returns an integer and by calling an array with an integer (like A[3] ), it always returns a value or undefined. explicitly check for the undefined value if you want to make sure application code is not broken.

1 Comment

Note: The Array.indexOf method is not available in IE 8 or earlier.
0

You may want to give below function a try. PHP.js is really a great collection of functions and salute to all contributors to make it what it is today.

http://phpjs.org/functions/in_array:432

1 Comment

Many a times PHP.js is a great place to learn many unexplored things with Javascript.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.