1

I have an array of strings, and I'm trying to define a function where imputing string "xyz" will search the array and return the index. "xyz" will be different each time the function is called.

I have tried this (JavaScript):

var data = ["abc","def","ghi","jkl","mno"];
\\ this array is actually much longer

look = function(a){return a = this;}
\\ at first I was trying data.findIndex("xyz")
\\ but Chrome Dev. tools said "xyz" is not a function

Params = function(x="abc"){
  y = data.findIndex(look,x);
  return y;
}

\\ Params("abc") should return 0
\\ Params("def") should return 1
\\ Params("ghi") should return 2
\\ etc.

I know I could do this with a for-loop, and cycle through all of the values in "data" but this seems inefficient. Is there a better way? Am I misunderstanding the "findIndex" method?

Wes Tomer
  • 319
  • 1
  • 13
  • Just use `indexOf()` – Paolo May 03 '19 at 19:42
  • the method you are looking for is [indexOf](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf). ([findIndex](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex) is a more generalised version that takes a function and returns the index of the first element that the function is `true` for) – Robin Zigmond May 03 '19 at 19:42
  • There's a typo in `function(a){return a = this;}` as well -- you want the equality operator, not the assignment operator here: `function(a){return a == this;}`; – Cᴏʀʏ May 03 '19 at 19:43

2 Answers2

2
const strings = ["abc","def","ghi","jkl","mno"];
const find = string => strings.indexOf(string)

find("abc") //return 0
Matteo Pagani
  • 545
  • 5
  • 14
0

Use array.indexOf, for example:

Params = function(x) {
    y = data.indexOf(x);
    return y;
}
user1039663
  • 1,230
  • 1
  • 9
  • 15