Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

175
Vistas
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)        
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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)

about 4 years ago · Juan Pablo Isaza Denunciar

0

A straightforward approach ...

const array = Array
  .from(
    { length: 50 },
    () => parseInt(Math.random() * 100 + 1),
  )
  .sort((a, b) => a - b);

// mutate/shorten `array`, remove all values equal to the minimum value.
array.splice(0, array.lastIndexOf(array[0]) + 1);

Proof of the above implementation ...

const array = Array
  .from(
    { length: 50 },
    () => parseInt(Math.random() * 100 + 1),
  )
  .sort((a, b) => a - b);

console.log({
  arrayLength: array.length,
  minValue: array[0],
  sorted: array,
});

// mutate/shorten `array`, remove all values equal to the minimum value.
array.splice(0, array.lastIndexOf(array[0]) + 1);

console.log({
  arrayLength: array.length,
  shortened: array,
});
.as-console-wrapper { min-height: 100%!important; top: 0; }

Similar tasks which mutate an array by actively removing/slicing items from it could be based on a more generic reject based approach ...

function reject(targetArray, condition, target) {
  const rejectedItemList = [];

  let idx = targetArray.length;
  const copy = [...targetArray];

  // Processing the array from RIGHT to LEFT keeps the `idx` always in sync
  // with both related array items, the one of the mutated and also the one
  // of the non mutated version of the processed target array reference.
  // Thus the `condition` always gets passed the non mutated shallow copy.

  while (idx) {
    if (
      // take *sparse array* into account.
      targetArray.hasOwnProperty(--idx) &&

      // [item, idx, copy] called within `target` context.
      condition.call((target ?? null), copy[idx], idx, copy)
    ) {
      // keep filling the list of rejected items
      // FROM its LEFT side while mutating the target array.
      rejectedItemList.unshift(targetArray.splice(idx, 1)[0]);
    }
  }
  // returns an array of rejected items
  // but not the processed and mutated
  // target array reference.

  return rejectedItemList;
}

const array = Array
  .from(
    { length: 50 },
    () => parseInt(Math.random() * 100 + 1),
  );
const minValue =  Math.min(...array);

console.log({
  arrayLength: array.length,
  minValue,
  array,
});
console.log({
  rejectedItems: reject(array, value => value === minValue),
  arrayLength: array.length,
  sorted: array.sort((a, b) => a - b),
});
.as-console-wrapper { min-height: 100%!important; top: 0; }

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda