Home > Back-end >  Looping through array and removing smallest number
Looping through array and removing smallest number

Time:03-06

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)        

CodePudding user response:

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)

CodePudding user response:

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; }

  • Related