Crys Ex
Crys Ex

Reputation: 335

Javascript/jQuery Get Array Element Index from element position/index

I know this question is a bit weird, but here's the example:

This is the array:

mesreponses = ["10700#NB - Purple#1#0", "10699#NB - Nude#1#0", "10698#NB - Navy#1#0", "10697#NB - Marple#1#0", "10696#NB - Grey-Melange#1#0", "10695#NB - Brown-Melange#1#1", "10701#3-6M - Brown-Melange#1#0", "10706#3-6M - Purple#1#0", "10705#3-6M - Nude#1#0", "10704#3-6M - Navy#1#0", "10703#3-6M - Marple#1#0", "10702#3-6M - Grey-Melange#1#0", "10707#9-12M - Brown-Melange#1#0", "10712#9-12M - Purple#1#0", "10711#9-12M - Nude#1#0", "10710#9-12M - Navy#1#0", "10709#9-12M - Marple#1#0", "10708#9-12M - Grey-Melange#1#0", "10713#18-24M - Brown-Melange#1#0", "10718#18-24M - Purple#1#0", "10717#18-24M - Nude#1#0", "10716#18-24M - Navy#1#0", "10715#18-24M - Marple#1#0", "10714#18-24M - Grey-Melange#1#0"]

Here's what I have to do: get the array position of any wanted element such as s_attrs = "NB - Purple" - it should return 0, when searching for "NB - Grey-Melange" it should return 1 and so on.

What I managed to do so far: get the INDEX of the element in the array, i.e.

console.log(String(mesreponses).indexOf(s_attrs));

So I just get the INDEX (i.e. for the first is 6, second 28, etc.) - can I use the index to get the Array's ELEMENT index? i.e. mesreponses[0], mesreponses[1], mesreponses[2], etc.

Or I just want to do something similar to jQuery.inArray(s_attrs, mareponse) but this does NOT work because it only searches for EXACT MATCHES.

Is there anything I could do, please?

Thanks!

Upvotes: 0

Views: 714

Answers (2)

ariel
ariel

Reputation: 16150

just iterate through it:

for (i = 0; mesreponses[i]; i++) {
  if (mesreponses[i].indexOf(s_attrs) >= 0) return i;
}
return -1;

Upvotes: 2

Richard Dalton
Richard Dalton

Reputation: 35793

This just requires a simple loop over the array:

function indexOfPartial(array, value) {
    for (var i = 0; i < array.length; i++) {
        if (array[i].indexOf(value) >= 0) {
            return i;
        }
    }
    return -1;
}

Which you can call as:

var index = indexOfPartial(mesreponses, 'NB - Nude');

http://jsfiddle.net/r57GN/

Upvotes: 3

Related Questions