Skip to content Skip to sidebar Skip to footer

Check If An Array Contains Part Of A String And Find The Index Number

const myArr = [ 'blue', 'red', 'orange', 'green' ]; I was wondering how to check if an array contains part of a string and the index number of the matching string. I’ve seen thi

Solution 1:

You can use some to check if there's at least one element verifying your condition :

var hasSome = myArr.some(function(v){ return v.indexOf("oran")>=0 })

If you need the index, a reverse for loop is the simpler solution :

for (var i=myArr.length; i--;) {
     if (myArr[i].indexOf("oran")>=0) break;
}

After the loop, i is -1 if no element matches, it's its index if one matches.

Note that in ES6 (the next version of JavaScript), you'll have the find and findIndex methods on arrays and the includes method on strings, which means you'll be able to do

var i = myArr.findIndex(v => v.includes("oran"));

Solution 2:

I think for a given Array If it is an exact match. You can use Array.includes.

const myArr = [ "blue", "red", "orange", "green" ];
console.log(myArr.includes("orange"))

If you are looking for just a fuzzy search you can use below codes.

const myArr = ["blue", "red", "orange", "green"];

// Create a helper method, and look for contains/includes in each itemconstcontains = (arr = [], m) => arr.some((txt) => txt.includes(m));

console.log(contains(myArr, "orang"))


// This is fuzzy search. Check in whole array. join array in string and check for contains/includesconsole.log(myArr.join("").includes("orang"));

// This is fuzzy search. Check in whole array. stringify array and check for contains/includesconsole.log(JSON.stringify(myArr).includes("orang"));

Note: Old browser may not support method includes. You can use index of instead

"test message".includes("test") /// true
//same as 
"test message".indexOf("test") !== -1 //true

Post a Comment for "Check If An Array Contains Part Of A String And Find The Index Number"