1

I was looking at some examples of using findIndex(), but I think they gave static examples by setting the search value as static variable inside the function.

I want to find the index of an object in an array so I can call it later. So far how I did it is as follows:

https://jsfiddle.net/osbb5zgc/5/

var array1 = [{name: "Adam", id: 23},{name: "Badam", id: 55}];
var target = 55;

var res = array1.findIndex(function(element){
    return element.id === target;
});

// Returns 1

It correctly returns 1 as is the index of {name: "Badam", id: 55}, BUT is there a better way of passing that target-variable into the function? Or will this work in most cases?

8
  • 1
    Just use indexOf Commented Jan 8, 2018 at 12:38
  • You're no doubt about to update this question to state that the items in the array are actually objects - not simple numbers. That will make this question entirely opinion based - "What is the best way to...." is by definition opinion based (My best != next persons best). You will need to specify more on what it is about this approach which does not fit the bill. Commented Jan 8, 2018 at 12:46
  • For your specific example, I can't think why findIndex won't be a suitable approach or how it can be improved upon. Can you specify your reservations against findIndex? Commented Jan 8, 2018 at 12:55
  • ...also your jsfiddle still points to the old version. Commented Jan 8, 2018 at 12:57
  • @Jamiec: Fiddle is now updated. I realise I should have rephrased the question. I was just referring to previous examples using findIndex to find objects, but who had the 'target' variable inside as a static value. I want to be able to add that value outside the function. Commented Jan 8, 2018 at 13:15

1 Answer 1

1

If the values in search_array is scalar in nature, then simply use indexOf

search_array.indexOf(target)

Demo

var search_array = [5, 12, 8, 130, 44];
var target = 44;

console.log("Index of target is " + search_array.indexOf(target));

However, if the value is an array or object, then findIndex is right method to use.

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

3 Comments

Thanks for your answer, actually, in the extension of this is that I want to have objects in the array, perhaps I should had made the question so.
@JUlinder For objects, findIndex is more suitable and indexOf won't work.
Good comment, I think I'll modify the question to be more accurate for what you're saying

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.