Iterating over an array to eliminate the least amount

I am attempting to use a for-loop in order to repeatedly find the smallest number in an array 50 times, and then remove it using splice(). Ultimately, my goal is to have an ascending list of numbers. However, I am encountering an issue where my program only identifies the smallest number in the original 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)        

Answer №1

Here is a simple method...

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

// Modify the `numbers` array, removing all instances equal to the smallest value.
numbers.splice(0, numbers.lastIndexOf(numbers[0]) + 1);

Evidence for the above procedure ...

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

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

// Modify the `numbers` array, removing all instances equal to the smallest value.
numbers.splice(0, numbers.lastIndexOf(numbers[0]) + 1);

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

Similar tasks that alter an array by actively slicing out elements from it may benefit from a more generic reject based approach ...

function reject(arr, condition, target) {
  const rejectedItems = [];

  let index = arr.length;
  const copyArr = [...arr];

  while (index) {
    if (
      // Consider *sparse arrays*.
      arr.hasOwnProperty(--index) &&

      // [element, index, copy] called within `target` context.
      condition.call((target ?? null), copyArr[index], index, copyArr)
    ) {
      rejectedItems.unshift(arr.splice(index, 1)[0]);
    }
  }

  return rejectedItems;
}

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

console.log({
  arrayLength: numberArr.length,
  minVal,
  numberArr,
});
console.log({
  rejectedItems: reject(numberArr, val => val === minVal),
  arrayLength: numberArr.length,
  sortedNumbers: numberArr.sort((a, b) => a - b),
});
.as-console-wrapper { min-height: 100%!important; top: 0; }

Answer №2

Perhaps a solution along these lines?

const array = [];
//initialize 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)

Alternatively, you could simplify by using array.sort() upfront.

const array = [];
    //initialize 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)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

JavaScript - Utilizing appendChild as soon as an element becomes available

I'm encountering an issue with my Chrome Extension where I am unable to detect some of the elements that I need to select within a page. var innerChat = document.querySelector('.chat-list'); My goal is to appendChild to this element, but t ...

Guidelines for positioning an object to float in the bottom right of a separate tag

I am trying to position an image at the bottom right of a parent div. The CSS solution I found from another answer did not work as expected, so I had to use JavaScript to achieve the desired result. Is there a way to do this without using JavaScript? (Pl ...

vue-awesome-swiper / The button's name is synchronized, causing all other swiper elements to move in unison

<template> <swiper v-for="item in items" :key="item.id" :options="swiperOption" ref="mySwiper" @someSwiperEvent="callback"> <swiper-slide>I'm Slide 1</swiper-slide> <swiper-slide>I'm Slide 2</swiper-slid ...

Issues with Ajax functionality in Rails

I believe my lack of knowledge in Ajax might be the reason for this issue. My goal is to continuously make ajax calls to my server as I am creating a demo app for learning purposes. Below is the code snippet: Code from job_status/index.html.erb file &l ...

Disable touch interactions on the body, only allow pinch-zoom on specific elements

I have been attempting to implement the following code: body { touch-action: none; } .left-side { touch-action: pinch-zoom; } <div class="left-side"><img src="image.jpg" /></div> The touch-action: none is functioning properly, but ...

How can I submit multiple dropdown menus when they are changed?

I recently added Four dropdown menus on my index.php page. <select name="filter_month" class="filters"> <option>Select a Month</option> <option value="1">January</option> <option value="2">February</optio ...

What is preventing me from creating accurate drawings on canvas?

I'm currently working on a paint application and facing an issue. When I place the painting board on the left side of the screen, everything works fine and I can draw without any problems. However, when I move it to the right side of the screen, the m ...

Display collection in Vue app

I am working with a model called files, which includes a property named response containing an array called errorMessages. In my Vue component, I am looking for a way to display these errors individually rather than as an array. Is there a solution for thi ...

Turning off form validation in AngularJS for a short period of time

Successfully implemented client side form validation using AngularJS, but now I want to test my server side validation by sending incorrect data. However, AngularJS is preventing me from doing so! Is there a way around this without disabling Javascript an ...

Using JSP in combination with JavaScript for creating dynamic templates

Implementing server-side HTML templating with JSP + JSTL allows for the generation of tables containing user data: <body> ... <table> <c:forEach items="${users}" var="user"> <tr> <td>${user ...

Verify if the contract address corresponds to a token and retrieve the token details, such as its symbol

Can I use web3 to retrieve token information such as symbol and total supply similar to the etherscan API pro endpoint tokeninformation by providing the contract address? I'm interested in determining whether the addresses I collect are tokens or reg ...

Preserving the newly added options above the current spinner choices

I'm looking for a way to enable users to add additional options to a spinner that displays options from an existing array list I created. Users can add options to the spinner while the app is running, but once it is closed and reopened, the added opti ...

Error occurred while initiating Angular frontend application with npm

https://i.sstatic.net/JCy3s.png > ng serve sh: ng: command not found npm ERR! code ELIFECYCLE npm ERR! syscall spawn npm ERR! file sh npm ERR! errno ENOENT npm ERR! <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c4b2a ...

Difficulties encountered when trying to load liquid using Javascript

Having trouble loading the Shopify liquid object {{product.price | json}} into JS, as it's displaying NaN with the current code on the front end. Any suggestions on how to properly pass liquid into JS? I've tried two functions but neither seem t ...

Using AngularJS ng-if to dynamically show header content according to the current route

Having trouble with my Single Page Application (SPA) where the header needs to change based on the user's route location. The code I've written seems correct, but I keep getting an error: TypeError: undefined is not a function Here's what t ...

Is it possible to transform an arrow function into a regular function?

Currently, I am working my way through the AJAX type ahead course in Javascript 30 by Wes Bos. As I progress through this course, I have made a conscious effort to minimize my use of ES6 features for the sake of honing my skills. If you want to see the fi ...

Combining values in the 3rd column and calculating the average of the 4th, 5th, and 6th columns for rows where 2 columns have the same value multiple times in Python/R

Details : Data: 0 77 1 2 3 5 0 78 2 4 6 1 0 78 1 2 3 5 3 79 0 4 5 2 3 79 6 8 2 1 3 79 1 2 3 1 Results : (calculate mean of columns 4, 5 and 6 for each row and sum column 3 when rows are identical) 0 77 1.0 2.0 3.0 5.0 0 78 3.0 3.0 4.5 3.0 3 79 7.0 4. ...

Setting limits on relational data in Nest.js involves utilizing the appropriate decorators and methods to restrict

In my Nest.js application, I am working with relational data and using the TypeOrm query builder to retrieve the data. Here is an example of how I am querying the data: async find() { return this.landingSectionNameRepository.createQueryBuilder(&apo ...

What is the reason behind the non-reversible nature of atob and btoa

Looking for a simple way to obscure answers to quiz questions in Markdown temporarily? The idea is to reveal the answers during the presentation, no need for secure encryption. Considered using atob('message I want to obfuscate') and letting stu ...

ng-repeat does not update model when using track by

I've been facing an issue with checklist-model while working with an array of check-boxes. The problem arises when I try to delete selected items within an ng-repeat loop. Everything works fine initially, but when I add track by $index along with ng-r ...