40

I have the following:

var gridData = {};
var TestRow = {
   "name": "xx",
   "description": "xx",
   "subjectId": 15
                };
gridData.push(TestRow)

How can I find out the index number of the new data that I just pushed into the gridData object?

  • possible duplicate of [JavaScript find array index with value](http://stackoverflow.com/questions/7346827/javascript-find-array-index-with-value) – Ryan Bigg Apr 22 '13 at 05:05
  • 3
    Wouldn't you want to figure out why the `push()` method doesn't exist on that object first? – alex Apr 22 '13 at 05:07

3 Answers3

83

First off, I'll assume the gridData is an array, not an object as you've shown in your sample code because an object doesn't have a .push() method, but an array does.

Use .length - 1 as the index to the last item you pushed onto the array or save the returned value from .push() which is the new length of the array. This will be the index of the element that you just pushed onto the array and will be valid until you modify the array before that index (adding or removing items before that index).

var testRowIndex = gridData.push(TestRow) - 1;
// then you can access that item like this 
var item = gridData[testRowIndex];

Though, this doesn't make a whole lot of sense since you already have the data right in TestRow. As usual, if you describe what problem you're really trying to solve, we can probably provide more useful answers.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • 1
    I don't think this is a great answer, since the length is not necessarily the index - in the case that something else is manipulating the array also. In my case, there is a timeout that removes items from the array, so length is not the same as index which is what the question asked. – Paul Haggo Mar 05 '14 at 22:32
  • 4
    @PaulHaggo - if you push a value onto the array, then `length - 1` is always the index of that item that you just pushed onto the array. If you then have other code that manipulates the array, then all bets are off - the index of that previous item is unknown and won't be known because it depends upon what the other code did to the array. The question asked for the index of the item that was "just pushed". This answers that question. – jfriend00 Mar 05 '14 at 22:39
  • 2
    I know what you mean, but the index you get is only valid as long as no items are ever removed from the array before that index. I can get the index with your method immediately, but if I try to use that value later, it may not refer to the element I thought it did. Your answer is still correct, but I don't think it's as helpful as it could be for people who don't understand arrays well. – Paul Haggo Mar 06 '14 at 02:48
  • @PaulHaggo - yes. The OP asked for `"the index number of the new data that I just pushed into the gridData object"`. See `"just pushed"` in that statement. There is NO way in javascript to get a dynamic index that will always point to a particular element of an array no matter how many items are added/removed from before it in the array. If you want something like, then you probably want a named property in an object rather than an array position. – jfriend00 Mar 06 '14 at 02:50
  • None of this is made clear, that's all I'm saying. My original comment does not say the answer isn't correct - it is correct. – Paul Haggo Mar 06 '14 at 02:52
  • 3
    @PaulHaggo - OK, valid point. I added some more verbage to make it clear that this index is good only as long as you don't insert/remove elements before that index. – jfriend00 Mar 06 '14 at 03:44
9

When you push the item into an array you will get the current length of the array as return value. Use it to find the index.

var gridData = [];
var TestRow = {
   "name": "xx",
   "description": "xx",
   "subjectId": 15
                };
var length=gridData.push(TestRow);
alert(length-1);

Array.push returns The new length property of the object upon which the method was called.

PSL
  • 123,204
  • 21
  • 253
  • 243
  • I did not intend to make this answer duplicate. But when i saw jfriend00 answered it by calculating array.length-1 i thought of answering this shortcut way of using the return value itself. – PSL Apr 22 '13 at 05:21
3

First go, i'll say it's similar to find-indexof-element-in-jquery-array

Anyhow, saw @jfriend00 and @PSCoder answering it brilliantly, I wanted to convey some alternative's to Find Index,

Assuming, you have your array as :-

var gridData = [];//{} Curly braces will define it as object type, push operations can take place with respect to Array's

and I have two or more data in that Array

var TestRow = {
        "name": "xx",
        "description": "xx",
        "subjectId": 15
    };
    var TestRow1 = {
        "name": "xx1",
        "description": "xx1",
        "subjectId": 151
    };

Now, I push these two data, like the way you have done. To find the Index of the pushed element, we can use, .indexOf and .inArray

var indexOfTestRow0 = gridData.indexOf(TestRow);// it returns the index of the element if it exists, and -1 if it doesn't.
    var indexOfTestRow1 = gridData.indexOf(TestRow1);// it returns the index of the element if it exists, and -1 if it doesn't.

    //Search for a specified value within an array and return its index (or -1 if not found).
    var indx1 = jQuery.inArray(TestRow, gridData);
    var indx2 = jQuery.inArray(TestRow1, gridData);

Thought of testing the stuff, so i tried something very simple like below:-

<head>
    <title></title>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<script>
    $(document).ready(function () {
        var gridData = [];//{} Curly braces will define it as Boject type, push operations can take place with respect to Array's
        var TestRow = {
            "name": "xx",
            "description": "xx",
            "subjectId": 15
        };
        var TestRow1 = {
            "name": "xx1",
            "description": "xx1",
            "subjectId": 151
        };
        gridData.push(TestRow);
        gridData.push(TestRow1);
        console.log(gridData);

        var indexOfTestRow0 = gridData.indexOf(TestRow);// it returns the index of the element if it exists, and -1 if it doesn't.
        var indexOfTestRow1 = gridData.indexOf(TestRow1);// it returns the index of the element if it exists, and -1 if it doesn't.

        //Search for a specified value within an array and return its index (or -1 if not found).
        var indx1 = jQuery.inArray(TestRow, gridData);
        var indx2 = jQuery.inArray(TestRow1, gridData);

        console.log(indexOfTestRow0);
        console.log(indexOfTestRow1);

        console.log(indx1);
        console.log(indx2);
    });


</script>
Community
  • 1
  • 1
Shubh
  • 6,693
  • 9
  • 48
  • 83
  • 1
    This is the only proper answer in this thread. Should be the accepted answer. If in the current accepted answer the array has been changed the index is wrong. The topic is to get the index, not the count minus one. – Redox Jun 24 '20 at 10:36