简体   繁体   中英

Splice not removing item from array javascript

I'm having problems with splice in my code, I don't know why is not working, I need to remove the minimum integer from the array.

Here's my code:

var players = [
    "Jug 1",
    "Jug 2",
    "Jug 3",
    "Jug 4"
];

var arrTotal = [72, 71, 70, 75];

function winners(arr) {
    var fstPlace = [], sndPlace= [];
    var min = Math.min.apply(null, arr);
    console.log(min);
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] == min) {
            fstPlace.push(arr.indexOf(min, i));
        }
    }
    if (fstPlace.length == 1) {
        console.log("1st: " + fstPlace);
        arr.splice(min, 1);
        console.log(arr);
    }
    else {
        console.log("Tie: " + fstPlace);
    }
}

winners(arrTotal);

You have to give the index of the item to be removed

 var players = [ "Jug 1", "Jug 2", "Jug 3", "Jug 4" ]; var arrTotal = [72, 71, 70, 75]; function winners(arr) { var fstPlace = [], sndPlace = []; var min = Math.min.apply(null, arr); snippet.log('min: ' + min); for (var i = 0; i < arr.length; i++) { if (arr[i] == min) { fstPlace.push(arr.indexOf(min, i)); } } snippet.log('fstPlace: ' + fstPlace) if (fstPlace.length == 1) { snippet.log("1st: " + fstPlace); arr.splice(fstPlace[0], 1); snippet.log('result: ' + arr); } else { snippet.log("Tie: " + fstPlace); } } winners(arrTotal); 
 <!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> <script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM