1

I'm new to javascript.

I'm trying to find the index of a specific element in an array. I read about that I can use findIndex to loop through an array. But it seems that findIndex only accept three arguments: element, index and array. What if I want change the object that is used to be compared.

For example, I want for find the index of string 'b' in array ['a','b','c'],

var position = ['a','b','c'].findIndex(function(element, index, array){return element==='b'})

but how do I pass 'b' as parameters that I can change to callback function

Thanks

1
  • 1
    "findIndex only accept three arguments" not really. findIndex accepts 2 arguments: callback and optional context. It is a callback that is being called with 3 arguments. Commented Jul 27, 2017 at 11:27

3 Answers 3

4

What about indexOf function? You just have to pass one argument, as searched element.

let arr = ['a','b','c'];

console.log(arr.indexOf('b'));

Sign up to request clarification or add additional context in comments.

Comments

3

You can define the wanted character from the outside context inside the callback function:

var wantedChar = 'c';
var position = ['a','b','c'].findIndex(function(element, index, array){return element===wantedChar})

console.log(position);

By doing so, you can wrap all that up in a function:

var findPos = function(arr, char){
    return arr.findIndex(function(element, index, array){return element===char});
}
console.log(findPos(['a','b','c'], 'c'));

Note: as already suggested, it makes more sense to use indexOf when just comparing strings. The findIndexfunction in combination with a custom callback is there for more sophisticated search, e.g. when dealing with complex structured objects.

Comments

-1

function getPosition(){
var position = ["a","b","c"];
var a = position.indexOf("b");
document.getElementById("demo").innerHTML = a;
}
<button onclick="getPosition()">button</button>
<p id="demo"></p>

1 Comment

Code only answer. Add some explanation to explain why.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.