'Looping through array and removing smallest number
i want to use a for-loop to find the smallest number in an array 50 times, then remove it with splice(). At last i want to end up with an ascending list of numbers. The problem i am having is my program only finds the smallest number for the 1st array and not the updated one.
array=[]
for(i=0; i<50; i++) {
array[i]=parseInt(Math.random()*100+1);
}
min = Math.min(...array)
minindex = array.indexOf(min);
splice = array.splice(minindex, 1)
console.log(splice)
Solution 1:[1]
Maybe something like this?
const array = [];
//create array
for (let i = 0; i < 100; i++) {
array.push(Math.floor(Math.random() * 100));
}
for (let i = 0; i < 50; i++) {
array.splice(array.indexOf(Math.min.apply(Math, array)), 1)
}
array.sort()
console.log(array)
Or more simple, use array.sort() at the beginning
const array = [];
//create array
for (let i = 0; i < 100; i++) {
array.push(Math.floor(Math.random() * 100));
}
array.sort();
for (let i = 0; i < 50; i++) {
array.splice(0, 1)
}
console.log(array)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | James |
