skip to Main Content

Please I’m trying to find minimum value inside my array and replace the minimum value with X for the same element not to be picked as minimum over again

Here is what I did
Var arr = [3,8,2,5,1]; Var minIndex;

While(arr.indexOf(‘X’) === -1){
minIndex = 0;
$.each(arr,function(index,value){
if (value < arr.[minIndex]){
minIndex = index;
}
});
arr[minIndex] = ‘X’;

}
Console.log(arr);

But only the first minimum which is 1 and is replaced with X

I don’t know what I’m doing wrong
Any help please

Replacing element of array with X

2

Answers


  1. You could use Array::reduce(). As mentioned by the author he wants to skip the minimum value for the next iteration, I guess we could remember the found minimum index:

    const arr = [3,8,2,5,1];
    
    // find the minimum value's index
    const [, minIdx] = arr.reduce(
      (acc, curr, idx) => acc[0] === undefined || curr < acc[0] ? [curr, idx] : acc,
      []
    );
    
    for(let i = 0; i < arr.length; i++){
      if(i === minIdx){
        continue; // skip minimum value
      }
      const val = arr[i];
      // do your stuff
      console.log(val);
    }
    Login or Signup to reply.
  2. If you really do not care about the array. Sort the array and remove them as you use them. There is no need to keep looking up the min.

    function getLeast(arr) {
      const remaining = [...arr].sort()
      return () => {
        if (!remaining.length) return undefined;
        return remaining.shift();
      }
    }
    
    const nums = [3, 8, 2, 5, 1];
    
    const genNums = getLeast(nums);
    console.log(genNums()); // 1
    console.log(genNums()); // 2
    console.log(genNums()); // 3
    console.log(genNums()); // 5
    console.log(genNums()); // 8
    console.log(genNums()); // undefined

    using a generator

    function* getLeast(arr) {
      const remaining = [...arr].sort()
      while (remaining.length) {
        yield remaining.shift();
      }
    }
    
    const nums = [3, 8, 2, 5, 1];
    
    const genNums = getLeast(nums);
    console.log(genNums.next().value); // 1
    console.log(genNums.next().value); // 2
    console.log(genNums.next().value); // 3
    console.log(genNums.next().value); // 5
    console.log(genNums.next().value); // 8
    console.log(genNums.next().value); // undefined
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search