0

I have an array with data that looks like this.

var objects = [
 {
   "rowid": 1,
   "Hostname": "11 Com"
},
 {
   "rowid": 2,
   "Hostname": "11 UMi"
},
 {
   "rowid": 3,
   "Hostname": "14 And"
   },
 {
   "rowid": 5,
   "Hostname": "23 A"
   }];

I'm trying to get the position of the element number of each object. Each object consists of their own "row id" and that's basically what I'm currently using to retrieve their element position with this function:

 function findCorrespondingNumber(hostname) { 
        function search(am, im) { 
        if (am.Hostname === hostname) { 
            index = im; return true; } 
        } var index;
     if (objects.some(search)) { 
        return objects[index]['rowid']; 
    } 
}
var correspNumb = findCorrespondingNumber(name) - 1;
var fiff = objects[correspNumb]["Hostname"];

The problem with the dataset is that numbers can sometimes skip sequence. The rowid 3 is followed by 5, instead of 4 as it should be. This is causing problem with further code so I need to have it so that the object with rowid 5 is read as the fourth object. How would I write that code?

ZoEM
  • 850
  • 9
  • 27
  • 1
    You want a `function` that will return `3` (the index) for a given input `23 A`? – haim770 Dec 13 '16 at 15:02
  • 1
    By "element number," do you mean array index? E.g., 0 - 3 in your example? – T.J. Crowder Dec 13 '16 at 15:03
  • Alternatively... would you like to get the array sorted by the rowid? This may help you if you then want to process the array in order. – scunliffe Dec 13 '16 at 15:04
  • Return `3` for the third object in the array. `23 A` is just the name of another property nothing to do with what I need I guess. I just used the above function to retrieve the rowid number based on a specific property name – ZoEM Dec 13 '16 at 15:04
  • This ***has*** to be a duplicate. *Edit:* Yup, was a bit tricky to find. – T.J. Crowder Dec 13 '16 at 15:06

1 Answers1

2

I think you're looking for Array#findIndex, which was added in ES2015. It accepts a predicate function and returns the index of the first entry for which the predicate returns a truthy value (or -1 if it never does):

var index = objects.findIndex(function(entry) {
    return entry.Hostname == hostname;
});

That gives you the 0-based index (so, 0 - 3 in your example). If you want the 1-based index (1 - 4 for your example; you did say "Return 3 for the third entry"), add one to the result.

There's also the closely-related Array#find, which does the same thing but returns the actual entry:

var entry = objects.find(function(entry) {
    return entry.Hostname == hostname;
});

Both are newish, but both can be shimmed/polyfilled.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875