Reputation: 311
I just found out that using the function array.push(value) using the same value name, will give the same index of the first item with the same value name.
Look at the example code following:
<p>Click the button to add a new element to the array.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits;
function myFunction() {
fruits.push("Orange");
var orange_index = fruits.indexOf("Orange");
document.getElementById("demo").innerHTML = orange_index;
}
</script>
If you run it, you will notice that the answer is "1" , that corrisponds to the first "Orange" item inserted into the array.
How can I avoid this behaviour ? I need to insert the same values into an array with different indexes.
Do I need to use multidimensional array ? I have a deck of cards, and I need to store the ranks and suits in array. So far I created two different arrays for ranks and suits, but I'm having this problem. I retrieve the ranks and suits separately, should I push them together into a new multidimensional array? how ?
Thanks
Upvotes: 1
Views: 2110
Reputation: 1021
Use .lastIndexOf()
instead of .indexOf()
, and it will get the last (most recently added) one instead of always the first.
Upvotes: 1
Reputation: 67505
The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.
Your array looks like following after you clicking in button :
["Banana", "Orange", "Apple", "Mango", "Orange"]
So when you try :
var orange_index = fruits.indexOf("Orange");
That will return the first index of Orange
like you saw in description, so normally it will return 1
.
Upvotes: 1