删除JS Array中的最小数字

时间:2016-05-14 10:11:42

标签: javascript arrays

我有一个数字数组[2,1,3,4,5,1],想要删除列表中最小的数字。但不知何故,我的IF语句被忽略了。

我检查了“数字[i + 1]”和“数字[i]”确实有效,但“数字[i + 1]< numbers [i]”没有...

function removeSmallest(numbers) {
  var smallestNumberKEY = 0;
  for (i = 0; i <= numbers.lenths; i++) {
    if (numbers[i + 1] < numbers[i]) {
      smallestNumberKEY = i + 1;
    }
  }
  numbers.splice(smallestNumberKEY, 1);
  return numbers;
}

document.write(removeSmallest([2, 1, 3, 4, 5, 1]));

10 个答案:

答案 0 :(得分:4)

您的代码中有拼写错误,数组没有lenths属性

function removeSmallest(numbers) {
  var smallestNumberKEY = 0;
  for (var i = 0; i < numbers.length - 1; i++) {
    if (numbers[i + 1] < numbers[i]) {
        smallestNumberKEY = i + 1;
        numbers.splice(smallestNumberKEY, 1);
    }
  }
  return numbers;
}

document.write(removeSmallest([2, 1, 3, 4, 5, 1]));

但是您的算法不适用于其他数组,例如[5, 3, 1, 4, 1],它也会删除值3

您可以使用Math.min函数找到最小值,然后过滤数组

function removeSmallest(arr) {
    var min = Math.min(...arr);
    return arr.filter(e => e != min);
}

答案 1 :(得分:3)

您可以使用Array#filter代替

&#13;
&#13;
function removeSmallest(arr) {
  var min = Math.min.apply(null, arr);
  return arr.filter((e) => {return e != min});
}

console.log(removeSmallest([2, 1, 3, 4, 5, 1]))
&#13;
&#13;
&#13;

答案 2 :(得分:1)

&#34;短&#34;使用Array.forEachArray.splice方法的解决方案:

function removeSmallest(numbers) {
    var min = Math.min.apply(null, numbers);
    numbers.forEach((v, k, arr) => v !== min || arr.splice(k,1));
    return numbers;
}

console.log(removeSmallest([2, 1, 3, 4, 5, 1]));  // [2, 3, 4, 5]

答案 3 :(得分:1)

这是一个单循环 Array#reduce Math.min的提案。

算法在第一个循环min中设置元素的值并返回一个空数组,因为实际元素是最小值,结果集不应包含最小值。

下一个循环可以有

  • 小于min的值,然后将a分配给min并返回原始数组的副本,直到前一个元素,因为找到了新的最小值并且所有其他先前的元素大于实际值并属于结果数组。
  • 大于min的值,然后将实际值推送到结果集。
  • 等于min的值,然后跳过vaue。

&#13;
&#13;
'use strict';

var removeSmallest = function () {
    var min;
    return function (r, a, i, aa) {
        if (!i || a < min) {
            min = a;
            return aa.slice(0, i);
        }
        if (a > min) {
            r.push(a);
        }
        return r;
    }
}();

document.write('<pre>' + JSON.stringify([2, 1, 3, 2, 4, 5, 1].reduce(removeSmallest, []), 0, 4) + '</pre>');
&#13;
&#13;
&#13;

答案 4 :(得分:1)

我更喜欢这样的工作。当Math对象遇到Array对象时,Spread运算符非常方便。

&#13;
&#13;
var ar = [2, 1, 3, 4, 5, 1];
ar.reduce((p,c,i,a) => (p == c && a.splice(i,1),p) , Math.min(...ar));
document.write(JSON.stringify(ar));
&#13;
&#13;
&#13;

答案 5 :(得分:0)

spliceindexOf的另一种解决方案:

array = [2, 1, 3, 4, 5, 1];

function replace(arr){
  arr = arr.slice(); //copy the array
  arr.splice( arr.indexOf(Math.min.apply(null, arr)),1)
  return arr;
  }

document.write( replace(array) ,'<br> original array : ', array)

编辑:制作数组的副本将避免修改原始数组

答案 6 :(得分:0)

我喜欢这个oneliner:list.filter(function(n) { return n != Math.min.apply( Math, list ) })

在此处查看:https://jsfiddle.net/rz2n4rsd/1/

function remove_smallest(list) {
    return list.filter(function(n) { return n != Math.min.apply( Math, list ) })
}

var list = [2, 1, 0, 4, 5, 1]
console.log(list) // [2, 1, 0, 4, 5, 1]

list = remove_smallest(list)
console.log(list) // [2, 1, 4, 5, 1]

list = remove_smallest(list)
console.log(list) // [2, 4, 5]

答案 7 :(得分:0)

我必须这样做,但我需要一个不会改变输入数组numbers并在O(n)时间内运行的解决方案。如果这就是你要找的东西,试试这个:

const removeSmallest = (numbers) => {
  const minValIndex = numbers.reduce((finalIndex, currentVal, currentIndex, array) => {
      return array[currentIndex] <= array[finalIndex] ? currentIndex : finalIndex
    }, 0)
  return numbers.slice(0, minValIndex).concat(numbers.slice(minValIndex + 1))
}

答案 8 :(得分:0)

缩短一根衬管。如果最小值多次存在,则只会删除一个。这可能是您想要的,也可能不是。

<?php
// as above
$accessKey = '<the key of your Cognitive Services>';
$endpoint = '<the endpoint of your Cognitive Services>';

// The `term` index is mapping to the `name` value of type `text` of tag `input` name `term`. 
// Case when use `method="POST"` in form tag, the value of `term` got by `$_POST` method
// Or case when use `GET` method, it change to `$_GET`.
$term = $_POST['term']; 

function BingWebSearch ($url, $key, $query) {
    /* Prepare the HTTP request.
     * NOTE: Use the key 'http' even if you are making an HTTPS request.
     * See: http://php.net/manual/en/function.stream-context-create.php.
     */
    $headers = "Ocp-Apim-Subscription-Key: $key\r\n";
    $options = array ('http' => array (
                          'header' => $headers,
                           'method' => 'GET'));

    // Perform the request and get a JSON response.
    $context = stream_context_create($options);
    $result = file_get_contents($url . "?q=" . urlencode($query), false, $context);
    echo $result;
    // Extract Bing HTTP headers.
    $headers = array();
    foreach ($http_response_header as $k => $v) {
        $h = explode(":", $v, 2);
        if (isset($h[1]))
            if (preg_match("/^BingAPIs-/", $h[0]) || preg_match("/^X-MSEdge-/", $h[0]))
                $headers[trim($h[0])] = trim($h[1]);
    }

    return array($headers, $result);
}

// Validates the subscription key.
if (strlen($accessKey) == 32) {

    print "Searching the Web for: " . $term . "\n";
    // Makes the request.
    list($headers, $json) = BingWebSearch($endpoint, $accessKey, $term);

    print "\nRelevant Headers:\n\n";
    foreach ($headers as $k => $v) {
        print $k . ": " . $v . "\n";
    }
    // Prints JSON encoded response.
    print "\nJSON Response:\n\n";
    echo $json;
    echo json_encode(json_decode($json), JSON_PRETTY_PRINT);

} else {

    print("Invalid Bing Search API subscription key!\n");
    print("Please paste yours into the source code.\n");

}
?>

答案 9 :(得分:0)

function sumOfPaiars(ints){
         var array = [];
         var min = Math.min(...ints)
         console.log(min)

 for(var i=0;i<ints.length;i++){
  if(ints[i]>min){
    array.push(ints[i])
  }
 }

return array
}