简体   繁体   中英

How to get index element in array with two the same elements?

var array = ["ab", "cd", "ef", "ab", "gh"];

Now, i have "ab" on position 0 and 3. I want to have index element only on position 3. I don't want "ab" on position 0. How can i get index element only on position 3? Please help.


second option: what if i have 5 elements or more? like this:

var array = ["ab", "cd", "ef", "ab", "gh", "ab", "kl", "ab", "ab"];

and now i want to have element on position 5?

Let's try this:

var lastIndex = 0;
var checkValue = 'ab';
var array = ["ab", "cd", "ef", "ab", "gh"];

for(var i = 0; i < array.length; i++){
    if(array[i] == checkValue) lastIndex = i;
};

In simple word:

  • lastIndex is the variable that contains the last matching index;
  • checkValue is the value you are looking for in the array;
  • the for cycle loop in the whole array and check if the actual item is equal to the checking value. If yes, update the lastIndex var.

I have maked function that can search anything from array

 var array = ["ab", "cd", "ef", "ab", "gh"]; function search(search, arr, callback) { for (var i = 0; i < arr.length; i++) { if (search === arr[i]) { callback(arr[i], i, arr); } } return -1; } search('ab', array, function(item, i) { alert(item + " : " + i); }); // or use this Array.prototype.search = function(search, callback) { for (var i = 0; i < this.length; i++) { if (search === this[i]) { callback(this[i], i, this); } } return -1; }; array.search('ab', function(item, i) { alert(item + " : " + i); }); 

I'd suggest:

function findAll (needle, haystack) {

    // we iterate over the supplied array using
   // Array.prototype.map() to find those elements
   // which are equal to the searched-for value
  // (the needle in the haystack):
    var indices = haystack.map(function (el, i) {
        if (el === needle) {
            // when a needle is found we return the
            // index of that match:
            return i;
        }
    // then we use Array.prototype.filter(Boolean)
    // to retain only those values that are true,
    // to filter out the otherwise undefined values
    // returned by Array.prototype.map():
    }).filter(Boolean);

    // if the indices array is not empty (a zero
    // length is evaluates to false/falsey) we
    // return that array, otherwise we return -1
    // to behave similarly to the indexOf() method:
    return indices.length ? indices : -1;
}

var array = ["ab", "cd", "ef", "ab", "gh"],
       needleAt = findAll('ab', array); // [0, 3]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM