Seeking assistance in incorporating items from one array into another array

I have a task involving two arrays - one named a, containing 5 values, and another named s which is currently empty. The objective is to identify the smallest value in array a, add it to array s, and then remove it from array a. Below is the code I have implemented:

            class Sorting {
                constructor () {
                    let getArr = document.getElementById('t');
                }

            findMin () {
                let a = [23, 30, 9, 10, 26];
                let s = [];

                for (let i = 0; i < a.length; i++) {
                    let min = i;
                    for (let j = i + 1; j < a.length; j++) {
                    if  (a[j] < a[min]) {
                    min = j;
                    }
                }
                
                s.push(a[min]);

                a.splice(min, 1);
                
                    if (i !== min) {
                    let x = a[i];
                    a[i] = a[min];
                    a[min] = x;                    
                    }
            
                }
                
                console.log(s)
                console.log(a)
            }
        }
            
        function main() {
        let p = new Sorting ();
        p.findMin();
    }

I am facing an issue where my program fails to properly remove the element from array a after adding it to array s.

When I remove the line a.splice(min, 1) and only keep s.push(a[min]), all the values from a end up in s. However, if I include both actions, the result I get is as follows:

s: [9, 23, 30]

a: [10, 26]

What I'm aiming for is:

s: [9, 10, 23, 26, 30]

a: []

I would appreciate any insights on why this is happening and how I can resolve it. Any assistance provided would be highly valued.

Answer №1

To process the array efficiently, you can iterate through the elements to find the minimum value and then use that index to splice the array and create a new array with the sorted values.

const
    numbers = [23, 30, 9, 10, 26],
    sorted = [];

while (numbers.length) {
    let minIndex = 0;
    for (let currentIndex = 1; currentIndex < numbers.length; currentIndex++) {
        if (numbers[currentIndex] < numbers[minIndex]) {
            minIndex = currentIndex;
        }
    }
    sorted.push(...numbers.splice(minIndex, 1));
}

console.log(numbers);
console.log(sorted);

Answer №2

const numbers = [25, 2, 5, 28, 10, 32];
const sortedNumbers = [];
let previousValue;
let leastValueIndex;

// Finding the least value in the array
for (let i = 0; i < numbers.length - 1; i++) {
    if (i === 0) {
        previousValue = numbers[i];
    }
    const difference = previousValue - numbers[i + 1];
    if (difference > 0) {
        previousValue = numbers[i + 1];
        leastValueIndex = i + 1;
    }
}

console.log("Index = " + leastValueIndex + " and Number = " + previousValue);
numbers.splice(leastValueIndex, 1);
sortedNumbers.push(previousValue);    
console.log(numbers);
console.log(sortedNumbers);

Hope this method helps. In this approach, I find the least value first along with its index in the array, remove it from the original array 'numbers', and add it to the 'sortedNumbers' array. You can also directly use the 'leastValueIndex' when pushing the value. For example,

sortedNumbers.push(numbers[leastValueIndex]);
numbers.splice(leastValueIndex, 1);

Answer №3

What if we took a slightly different approach to solving this problem? Maybe something like this:

let a = [23, 30, 9, 10, 26];
let s = [];
let sorted = a.slice().sort((a, b) => a - b);
s[0] = sorted[0]; //now our 's' variable holds the smallest number
a.splice(a.findIndex(elem => elem == s[0]), 1)
console.log(a);
console.log(s);

Here, we are identifying the smallest number in the array by sorting it from smallest to largest. We then use .findIndex() to locate the index of the smallest number and .splice to delete it.

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

Nullify the unfulfilled fetch call

When a value is entered in the search bar on the webpage, it gets added to a URL and used to retrieve JSON data. Everything works smoothly, but if a value is inputted that the API doesn't have information for, a null response is returned. The questio ...

Updating $scope from another controller in AngularJS

I am facing an issue where I need to update the $scope inside a directive's link function. Here is what my controller and directive look like: $scope.current = 0; angular.module('myAPP') .directive('post', function() { ...

Is there a way to execute a node script via command line sans the need for installation and external packages?

Is there a way to execute a node script from the command line during development without actually installing anything, but still having access to installed packages using npm install <...>? When I try node ./bin/my_script.js, the script does not reco ...

What is the method for storing API status JSON in the state?

Can anyone help me figure out why the json in the register state is returning an empty object after console.log(register); from that state? import React, { useEffect, useState } from "react"; import { Formik } from "formik"; // * icons ...

Capturing the value of an input field within a controller in AngularJS

I have been programming with JSP and Angular JS. Currently, I am faced with a scenario where I need to work with a JSP page containing a hidden input field. To set the value of this input field, I am using a session attribute like so: String policy = (S ...

Track the number of visits originating from email links with query strings

Our strategy involves sending follow-up emails regarding our products, and I am interested in monitoring their effectiveness. This is my proposed approach: To measure the impact of these follow-up emails, I plan to update the URL in the email hyperlink t ...

How come JavaScript variables are able to persist on JQuery Mobile multi-page templates on desktop browsers, but not on mobile browsers?

My website was created using the jQuery Mobile multi-page template. While testing it on Chrome desktop, I noticed that my JavaScript variables (comics and checkedItems) retain their values when navigating between pages. However, on mobile devices, these ar ...

The absence of the function crypto.createPrivateKey is causing issues in a next.js application

For my next.js application, I am utilizing the createPrivateKey function from the crypto module in node.js. However, I encountered an issue as discussed in this thread: TypeError: crypto.createPrivateKey is not a function. It seems that this function was a ...

What is the best way to append an element to an array using the index value "array[total number of items in array + 1]"?

I'm currently working on a software project that involves enabling users to input an element to an array: #include <stdio.h> #include <cs50.h> int main(void) { string words[] = {"apple", "bear", "cards"}; ...

Utilizing webpack to import both d3 and d3-cloud libraries

I've been attempting to integrate d3 and d3-cloud (for word cloud) into my AngularJs(v - 1.4) app by using: import d3 from 'd3' import d3Cloud from 'd3-cloud'. However, when trying to use d3-cloud with d3.layout.cloud(), ...

When JSON.stringify is used to convert an object to JSON, it will result in

I'm having difficulty creating a JSON object for transmission over the network. The particular array I'm dealing with looks like this in the Chrome debugger. event: Array[0] $$hashKey: "02Q" bolFromDB: 1 bolIndoor: null ...

Is there a method available to minimize the size of a local storage list containing strings?

Hey there, I am trying to load a large 2.5MB json file in my browser so that I can use it for some typeAhead functions. Unfortunately, I'm facing an issue with my local storage being constantly full. When using Firefox, I receive the following error ...

Mapping routes in ExpressJS

I am interested in developing a programmatic route generator. Within my project, I have a module called ./utils/crud.js structured as follows: const express = require('express'); const router = express.Router(); module.exports = function (Mode ...

"Encountering a problem with ThreeJs graphics rendering

I recently developed an application using ThreeJs, but I encountered a strange issue. After rendering the 3D graphics, the window appears blank. However, when I click on full screen or adjust the window size, the output becomes visible. Check out Screen s ...

Utilizing JavaScript files within Angular2 components: A guide

I need to insert a widget that runs on load. Typically, in a regular HTML page, I would include the script: <script src="rectangleDrawing.js"></script> Then, I would add a div as a placeholder: <div name="rectangle></div> The is ...

Executing React's useEffect hook twice

As I work on developing an API using express.js, I have implemented an authentication system utilizing JWT tokens for generating refresh and access tokens. During testing with Jest, Supertest, and Postman, everything appears to be functioning correctly. O ...

What is the method for determining the level based on the provided experience points?

I've created a formula that can calculate experience based on specific levels and another formula that calculates the level based on given experience. However, there seems to be an issue with the second function as it is not returning the expected val ...

my initial attempt at using Firebase cloud functions

I'm currently attempting to create my first Firebase Cloud Function. My goal is to take the value of the 'name' field from the 'amr' document and add it to the 'ahmed' document under a new field called 'newName' ...

What is the best way to transform the format of an array output?

In my Ruby code, I'm working with an narray that is automatically generated and has the form [x,y], where x and y are both integers. My goal is to convert [x,y] into a specific type of string: "p\.x\.y" So far, I've been struggling t ...

Navigate to a fresh web page without encountering any script loading issues

I am currently working on a web application that loads new pages without requiring the browser to reload. While some pages load perfectly fine, others are causing errors due to missing scripts. The code snippet below is used to load a new page: function lo ...