0

I have an array like

var x=["A|a","B|b","C|c"];

Now, i want to find the index for 'c' which is x[2]. So, we can get the index value of 'c' by running a "for" loop and splitting each string with the seperator of '|' and we can find it.

But, is there any simple way to find the value?

2
  • You can use indexOf in this case x.indexOf("c"); Commented Jul 21, 2015 at 10:43
  • 1
    If all of your array elements are in that format, why split it at all? x.indexOf('C|c')? Commented Jul 21, 2015 at 10:44

3 Answers 3

2

var x=["A|a","B|b","C|c"];
var index = -1;
x.forEach(function(e, i){
  if (e.indexOf("c") !== -1) index = i;
})
alert(index);

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

Comments

2

You can try out something like this

Array.prototype.customIndexOf = function(str){
    var s = str.toUpperCase()+"|"+str;
    return this.indexOf(s);
};

var x=["A|a","B|b","C|c"];
x.customIndexOf('c');

One better approach

Array.prototype.customIndexOf = function(str, func){
    var s = func(str);
    return this.indexOf(s);
}

var x=["A|a","B|b","C|c"];
x.customIndexOf('c', function(arg){
    return arg.toUpperCase()+"|"+arg.toLowerCase();
});

2 Comments

I'd suggest a slight modification: var s = str.toUpperCase() + '|' + str.toLowerCase(); that way it doesn't matter whether the passed-in string is lowercase or uppercase.
Thats grt. One better solution is we can pass a callback where user can modify his search string based on requirement. I have just updated my answer.
1

How about this:

for(var i in x){
if(x[i].indexOf('c') != -1)
    alert(i);
}

1 Comment

Welcome to stack overflow, I'm reviewing your post. A few tips on how you can improve your posts and your odds of having your answer accepted / upvoted. First and foremost, make sure you explain how your solution solves the problem. Optionally, try to provide a working fiddle. Also optionally but preferred, It also helps to link to related documentation. How to answer: stackoverflow.com/help/how-to-answer

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.