How to Find the Index/Position of an element in an array

This js function will find the index of an array element with the given value in an array.
for Example you are having an array like

var mnuArray = new Array(“Groups”,”Services”,”Applications”);

And want to know the index/position of and element in an array, then
you can call mnuArray.findIndex(“Services”);
This will return “1”.

This will be helpful if you are having a large size array/the elements are unknown which you have populated from an dB

Array.prototype.findIndex = function(value){
var ctr = "";
for (var i=0; i < this.length; i++) { // use === to check for Matches. ie., identical (===), ; if (this[i] == value) { return i; } } return ctr; };

And advanced version of this function is,
If you want to do the same in the case of multidimensional arrays
then use the following

Array.prototype.findIndexByCol = function(value,cIdx){
var ctr = "";
for (var i=0; i < this.length; i++) { // use === to check for Matches. ie., identical (===), ; if (this[i][cIdx] == value) { //alert(this[i][cIdx]+"===="+value); return i; } } return ctr; };

19 Replies to “How to Find the Index/Position of an element in an array”

  1. you saved me some time here – I couldn’t believe that javascript didn’t have a getPos() function –

  2. Scratch that.. being a bit dim… This would do it:

    Array.prototype.findIndexByCols = function(value1,cIdx1,value2,cIdx2){
    var ctr = ”;
    for (var i=0; i < this.length; i++) {
    // use === to check for Matches. ie., identical (===), ;
    if (this[i][cIdx1] === value1 && this[i][cIdx2] === value2) {
    ////#console.log(this[i][cIdx]+"===="+value);
    return i;
    }
    }
    return ctr;
    };

  3. Thank you so much! My text book for school doesn’t cover arrays very well (which is kind of pathetic), and this was just what I was looking for. Thanks again.
    Jennie

  4. Meaning if my array of objects is:

    var mnuArray = {‘A’:’foo’,’B’:’bar’};

    and I want to know the position of ‘bar’

    mnuArray.findIndexByCol(‘bar’,?);

    Thanks!

  5. You should mention that with this technique you are extending the array prototype, which might affect other scripts and generally speaking can be a problematic approach.

Leave a Reply to Syed Cancel reply

Your email address will not be published. Required fields are marked *