Sort the array first, then find the position of the specified value in the array, and finally return the index corresponding to the position.
Example: where([1,2,3,4], 1.5)
should return 1
. Because after 1.5
inserting into the array [1,2,3,4]
, it becomes [1,1.5,2,3,4]
, and the 1.5
corresponding index value is 1
.
Likewise, where([20,3,5], 19)
it should return 2
. Because the array will be sorted first [3,5,20]
, it will become after 19
inserting into the array , and the corresponding index value is .[3,5,20]
[3,5,19,20]
19
2
Idea: Insert the parameters into the array first, then sort the array in ascending order, and finally find the position of the parameter in the sorted array.
unction where(arr, num) {
//put the parameters into the array
arr.push(num);
//sort the array in ascending order
arr.sort(function(x,y){
return x - y;
});
// Return the position of the parameter in the array
return arr.indexOf(num);
}