Home > Software engineering >  Finding & Removing the top 10 largest numbers and the top 10 smallest numbers of the array
Finding & Removing the top 10 largest numbers and the top 10 smallest numbers of the array

Time:02-23

I would like to ask about an issue regarding an array I have generated an array with 100 integers

//Generate 100 numbers
        var arr = [];
        while(arr.length < 100){
            var r = Math.floor(Math.random() * 100)   1;
            if(arr.indexOf(r) === -1) arr.push(r);
        }
        console.log(arr);

My issue is Finding and Eliminating the top 10 maximum and Minimum of the array

        //Find the Minimum 


        for (let i=0; i != 10; i  ){

            arr.splice(Math.min(...arr), 1)

        }
            

        //Find the Maximum

        
        for (let i=0; i != 10; i  ){
            

                arr.splice(Math.max(...arr), 1)
            
        
        }

and the result is only 90 of the array is eliminated is the maximum & minimum code fighting?

CodePudding user response:

You need to get the index of the max and min value from the arr and then use splice. Also change i != 10; to i<10

var arr = [];
while (arr.length < 100) {
  var r = Math.floor(Math.random() * 100)   1;
  if (arr.indexOf(r) === -1) arr.push(r);
}
for (let i = 0; i < 10; i  ) {
  const min = arr.indexOf(Math.min(...arr));
  arr.splice(min, 1)

}
for (let i = 0; i < 10; i  ) {
  const max = arr.indexOf(Math.max(...arr));
  arr.splice(max, 1)

};

console.log(arr.length)

CodePudding user response:

You can sort the array and then use the splice method to remove the first and last 10 elements.

var arr = [];
while (arr.length < 100) {
  var r = Math.floor(Math.random() * 100)   1;
  if (arr.indexOf(r) === -1) arr.push(r);
}

arr.sort((a, b) =>  a -  b);

arr.splice(0, 10);

arr.splice(80, 10);

console.log(arr.length);
  • Related