I have been working on a versatile function that can perform various tasks related to finding a specific value in a list or array. Below is the code I have come up with:
function findInArray(needle, arr, exact, sensitive) {
if (needle && arr) {
var hayLength = arr.length
for (var i = 0; i < hayLength; i++) {
if (arr[0].length >= 0) {var haystack = arr[i][0];}
else {haystack = arr[i];}
if (exact && sensitive && (haystack === needle)) {return i;}
else if (exact && !(sensitive) && (haystack == needle)) {return i;}
else if (!(exact) && sensitive && (haystack.toLowerCase().search(needle.toLowerCase()))>-1) {return i;}
else if (!(exact) && !(sensitive) && haystack.search(needle)>-1) {return i;}
}
}
return -1;
}
Although I believe the code can be optimized further, I am facing an issue with the third condition when attempting to ignore case sensitivity to match a string in a list. For example:
var arr = ["Partner1", "Partner2"]
var needle = "partner1"
var n = findInArray(needle, arr, true, false);
It returns -1.
I aim for this function to be able to work with both 1D and multidimensional lists and to find substrings (e.g. match "Google" and "Googler").
Answered: Drawing inspiration from responses by @NoobishPro and @tehhowch, the following optimized code resolves the sensitivity parameter efficiently:
function findInArray(needle, arr, exact, sensitive) {
exact = exact !== false;
sensitive = sensitive !== false;
//Accounting for sensitivity parameter to enhance performance
if (!sensitive) {
needle = needle.toLowerCase();
}
//Determining array length
var hayLength = arr.length;
for (var i = 0; i < hayLength; i++) {
//Setting haystack
var haystack = arr[i];
//Checking for nested arrays and handling them recursively
if (haystack.constructor == Array) {
return findInArray(needle, haystack, exact, sensitive);
}
//Performing additional lowercasing if sensitivity is disabled
if (!sensitive) {
haystack = haystack.toLowerCase();
}
//Handling different scenarios based on exact and sensitivity settings
if (exact && sensitive && (haystack == needle)) {
return i;
} else if (exact & (haystack == needle)) {
return i;
} else if (!exact & (haystack.search(needle)) > -1) {
return i;
}
}
return -1;
}