数组排序并插入值算法JavaScript

9次阅读

共计 405 个字符,预计需要花费 2 分钟才能阅读完成。

问题:

先给数组排序,然后找到指定的值在数组的位置,最后返回位置对应的索引。

示例:

举例:where([1,2,3,4], 1.5) 应该返回 1。因为 1.5 插入到数组 [1,2,3,4] 后变成[1,1.5,2,3,4],而 1.5 对应的索引值就是 1。

同理,where([20,3,5], 19) 应该返回 2。因为数组会先排序为 [3,5,20],19 插入到数组 [3,5,20] 后变成[3,5,19,20],而 19 对应的索引值就是 2。

解答:

function where(arr, num) {
// Find my place in this sorted array.
    arr.push(num);
    var newArr = arr.sort(function(a,b){return a-b});
    return newArr.indexOf(num);
}


where([2, 20, 10], 19);

链接:

https://www.w3cschool.cn/code…

正文完
 0