-1

How can i find matching element in array, for example

i want to find word in array element "Black" Array element is : ["Black footbal scarf"] So i understand how to match this by converting array to string, but how can i do it exactly with array elements

var color = "Black";

var arr = ["Black footbal scarf", "Blue footbal scar", "Red footbal scar"];
//Converting to string WORKS
alert(arr.join("").indexOf(color));

alert(arr.indexOf(color));

So i need to get array index of the color from variable.

Andrew
  • 1,507
  • 1
  • 22
  • 42
  • A simple [Google Search](https://stackoverflow.com/questions/237104/how-do-i-check-if-an-array-includes-an-object-in-javascript) would have sufficed. – Angel Politis Dec 03 '17 at 09:42

3 Answers3

2

Just iterate over the array's strings and use .indexOf() on each index. If one results in >= 0, you have your index value.

var color = "Black";
var arr = ["Black footbal scarf", "Blue footbal scar", "Red footbal scar"];
var i = 0;
var l = arr.length;

for (i = 0; i < l; i++) {
    if (arr[i].indexOf(color) >= 0) {
        // var i is your desired index.
    }
}

Edited: "> 0" was of course wrong, must be ">= 0".

iquellis
  • 979
  • 1
  • 8
  • 26
  • Thank You, i forgot that you need check specific el, not whole array – Andrew Dec 03 '17 at 09:38
  • You're welcome, please regard my update, I made a bug ;-) – iquellis Dec 03 '17 at 09:39
  • by the way what will be faster to iterate through array, standart for loop or forEach? – Andrew Dec 03 '17 at 09:39
  • In this example it does not really matter, I think. The important thing is, that you should not count the stack on every loop step (updated the example for that). Usually foreach is the one to go for, if you do not need the current index' value. In this case, I understood that you actually need your index to re-access the array arr. Just do whatever fits best to your code in this case. – iquellis Dec 03 '17 at 09:43
0

You can iterate over the array, checking each element for the word.

var color = "Black";

var arr = ["Black footbal scarf", "Blue footbal scar", "Red footbal scar"];

let index = 0;
for (let word of arr) {
  if (word.includes(color)) {
    console.log(index);
    console.log(word);
  }
  index++
}
codejockie
  • 9,020
  • 4
  • 40
  • 46
0

Try using the split function in Javascript

var color = "Black";
var arr = ["Black footbal scarf", "Blue footbal scar", "Red footbal scar"];
var stringSplit = arr.split(/(?:,| )+/);
alert(stringSplit.indexOf(color));
Kunal Mukherjee
  • 5,775
  • 3
  • 25
  • 53