Doing this real quick so i'm sure it can be improved.
There are two ways coming in my mind, the first would be using .indexOf
:
<script type="text/javascript>
$(document).ready(function()
{
var selectedVal = 'asd';
var selectedIndex;
var arrayHolder; //should hold the array the value was found in
var arr1 = ['huh', 'asd'];
var arr2 = ['asdasd'];
var arr3 = ['asdasdasd'];
var arr4 = ['asdasdasdasd'];
//arr1
arrayHolder = arr1;
selectedIndex = arrayHolder.indexOf('asd');
if (!selectedIndex)
{
//arr2
arrayHolder = arr2;
selectedIndex = arrayHolder.indexOf('asd');
if (!selectedIndex)
{
//arr3
arrayHolder = arr3;
selectedIndex = arrayHolder.indexOf('asd');
if (!selectedIndex)
{
//arr4
arrayHolder = arr4;
selectedIndex = arrayHolder.indexOf('asd');
if (!selectedIndex)
{
alert(selectedVal + ' not found in all 4 arrays.');
}
}
}
}
//By here, you should know if a value was found and in which array
alert(arrayHolder);//contains the array in which the value was found
alert(selectedIndex);//The index number where it was found
//test
console.log(arrayHolder[selectedIndex]);
});
</script>
The second way is to do it using jQuery's inArray
:
<script type="text/javascript>
$(document).ready(function()
{
var selectedVal = 'asd';
var selectedIndex;
var arrayHolder; //should hold the array the value was found in
var arr1 = ['huh', 'asd'];
var arr2 = ['asdasd'];
var arr3 = ['asdasdasd'];
var arr4 = ['asdasdasdasd'];
//check first array
arrayHolder = arr1;
selectedIndex = $.inArray(selectedVal, arrayHolder);
//check if found in first array, if not check next array
if (!selectedIndex)
{
arrayHolder = arr2;
selectedIndex = $.inArray(selectedVal, arrayHolder);
//check if found in second array, if not check next array
if (!selectedIndex)
{
arrayHolder = arr3;
selectedIndex = $.inArray(selectedVal, arrayHolder);
//check if found in third array, if not check next array
if (!selectedIndex)
{
arrayHolder = arr4;
selectedIndex = $.inArray(selectedVal, arrayHolder);
//check if found in third array, if not check next array
if (!selectedIndex)
{
alert(selectedVal + ' not found in all 4 arrays.');
}
}
}
}
//By here, you should know if a value was found and in which array
alert(arrayHolder);//contains the array in which the value was found
alert(selectedIndex);//The index number where it was found
//test
console.log(arrayHolder[selectedIndex]);
});
</script>
.indexOf support
NOTE:
.indexOf() is not supported on all browsers (specifically speaking for IE).
So if you want to use indexOf(), you should use the below code above all first, to add support for it in all browsers (credit to mozilla for the code).
<script type="text/javascript">
if (!Array.prototype.indexOf)
{
Array.prototype.indexOf = function(elt /*, from*/)
{
var len = this.length >>> 0;
var from = Number(arguments[1]) || 0;
from = (from < 0)
? Math.ceil(from)
: Math.floor(from);
if (from < 0)
from += len;
for (; from < len; from++)
{
if (from in this &&
this[from] === elt)
return from;
}
return -1;
};
}
</script>