0

Цhat is the most effective way to find an element position within an array, if we got access to the element itself?

var arr = [];
for (var i = 0; i < 10; i++) {
    arr[i] = {test: Math.floor(Math.random() * 101)}
}
var test = arr[Math.floor(Math.random() * 11)];

Now how can I get the position of the element that test refer to?

1
  • May be in this way var pos=Math.floor(Math.random() * 11); Commented Dec 7, 2010 at 11:09

2 Answers 2

1

I'd just store the position when generating it here, like this:

var arr = [];
for (var i = 0; i < 10; i++) {
    arr[i] = {test: Math.floor(Math.random() * 101)}
}
var index = Math.floor(Math.random() * 11);
var test = arr[index];
//index is the position
Sign up to request clarification or add additional context in comments.

2 Comments

Isn't that memory intensive? (assuming I have a large multi-dimensional array where each cell is occupied)
@GZaidman - I wouldn't say so...the alternative is of searching via .indexOf() is much more CPU intensive, when you already know the result.
0

I assume that the random generation is just an example.

Now if you've got a reference to an element and want to find out its index you can use Array.indexOf method. It's a new feature so not all browsers support it natively, but it's easy to implement. A bare-bone solution would look like:

if (!Array.prototype.indexOf) {
  Array.prototype.indexOf = function (searchElement) {
    var len = this.length >>> 0;
    for (var i = 0; i < len; i++) {
      if (searchElement === this[i]) return i;
    }
    return -1;
  };
}

Now you can use it as:

index = array.indexOf(elem)    // index from an element reference
examp = [5,8,12,5].indexOf(12) // 2

Comments

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.