
Likewise, getIndexToIns(, 19) should return 2because once the array has been sorted it will look like and 19 is less than 20 (index 2) and greater than 5 (index 1). For example, getIndexToIns(, 1.5) should return 1because it is greater than 1 (index 0), but less than 2 (index 1). Algorithm instructions Return the lowest index at which a value (second argument) should be inserted into an array (first argument) once it has been sorted. The method findIndex also takes a callback. We have to sort an array of numbers from least to greatest and find out where a given number would belong in that array. The method findIndex is used to return the index of the first array element that passes a certain test function. This challenge gives us a glimpse into the wonderful world of sorts. There are all kinds of sorts: bubble sort, shell sort, block sort, comb sort, cocktail sort, gnome sort - I’m not making these up! Naturally, if you remove or add entries (or change their prop2 values), you need to update your mapping object as well.Sorting is a very important concept when writing algorithms. Then if you need to find the entry with prop2 = "yutu", you can do this: var entry = prop2map (Or, again, you could use a for loop or any of your other options.) Your various iteration options are covered in this other answer.īut if you're always going to be using the same property for this lookup, and if the property values are unique, you can loop just once and create an object to map them: var prop2map =

The function I've given it saves the index of the matching entry, then returns true to stop the iteration. That uses the new(ish) Array#some function, which loops through the entries in the array until the function you give it returns true. However, on a system with ES5 features (or if you install a shim), that iteration can be done fairly concisely: var index If the condition changes a lot, then you'll have to loop through and look at the objects therein to see if they match the condition. The indexOf() method returns the index of the first occurrence of the given element in an array and returns -1 when it doesnt find a match. You cannot, something has to iterate through the array (at least once).


How can I get the index of the object tha match a condition (without iterate along the array)?
