-4

Very close but slightly more complex than this question I have an array and I want to obtain the index of the array of the first occurrence of a value of a given object of this array.

My array has several objects of integer and text, and has an id object of integers (which I call with this instruction wup[i].id).

[edit] The array comes from reading a csv file with header with papaparse.

 wup = ["id", "cityName", etc ... ]
       [20002, "Tokyo",   etc ... ]
       [20003, "Goiânia", etc ... ]

It is in this id object only that I want to find the input value and finally get the index of this input value. This is certainly using indexOf but how to focus the search only in the id object?

[edit] the instruction that fails is the following (try to find the occurrence of tn[iter].idOri in the array wup, that I expect to retrieve in the variable iOri):

 var iOri = wup.indexOf(tn[iter].idOri);

Hoping it is clear enough.

  • please add an example of the array, the wanted item and the needed result. please add some code, you tried. – Nina Scholz Sep 14 '16 at 18:04
  • Off topic: There are no `column` in Array, same to: you can't define a column inside an Array. – Tân Sep 14 '16 at 18:11
  • I did my best to add some code and to be as precise as possible, considering my poor understanding of Javascript. In my view this table has columns with headings. – the world is not flat Sep 15 '16 at 09:00

1 Answers1

1

There are lots of ways to do this, map your array down to a flat array of ids:

var myId = 3;
var ids = array.map(function(obj) {
   return obj.id;
});
var index = ids.indexOf(myId);

A more succinct (and better - because it only requires one iteration) method would be to use Array.findIndex:

var myId = 3;
var index = array.findIndex(function(obj) {
   return obj.id === myId;
});

With es6:

var myId = 3;
var index = array.map(obj => obj.id).indexOf(myId);

or

var myId = 3;
var index = array.findIndex(obj => obj.id === myId);
Rob M.
  • 35,491
  • 6
  • 51
  • 50
  • I provide the instruction that worked in my case, derived from the third solution proposed by Rob: `var iOri = wup.map(obj => obj.CityCode).indexOf(tn[iter].idOri);` – the world is not flat Sep 16 '16 at 07:23