Reputation: 21
//Here is my code:
function removeSmallest(arr) {
var min = Math.min.apply(null, arr);
return arr.filter((e) => {return e != min});
}
console.log(removeSmallest([2,1,3,5,4], [5,3,2,1,4], [2,2,1,2,1]));
/*The issue is that I need the third array to output [2,2,2,1]. The code is actually doing what I am telling it to do by removing the smallest number in each array but for the sake of my problem, I need it to only take out one of the ones(if that makes sense). Appreciate any help! */
Upvotes: 0
Views: 255
Reputation: 17388
You just need to change your logic slightly. You find the minimum number in the array, then use that to find the first index of that number, and remove that specific number.
function removeSmallest(arr) {
var min = Math.min.apply(null, arr);
arr.splice(arr.indexOf(min), 1);
return arr;
}
Upvotes: 2
Reputation: 208
if you want to remove only the first occurrence in the array then somehow like that:
function removeSmallest(arr) {
var min = Math.min.apply(null, arr);
var count = 0;
return arr.filter((e) => {
if(e != min || count > 0) {
return true;
}
else if(e == min) {
count++;
return false;
}
});
}
Upvotes: 0