JavaScript Array Sort and Insert Value Algorithm Challenge

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.5inserting into the array [1,2,3,4], it becomes [1,1.5,2,3,4], and the 1.5corresponding 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 19inserting into the array , and the corresponding index value is .[3,5,20][3,5,19,20]192

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);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324819537&siteId=291194637