Issue with Angular Js: Trouble inserting array values post sorting

Hey everyone, I'm facing a challenge with AngularJS. I need to display the steps for selectionSort and here is my code:

var myApp = angular.module('myApp',[]);

var arraymain = [];

myApp.controller('myController',function($scope) {
    $scope.array2 = [];
    $scope.selectionSort = function(list) {
    n = list.length;
    temp2 = list;
    for(i = 0; i < n-1; i++) { //need to do n-2 passes
        i_min = i;
        //finding minimum index
        for(j = i+1; j < n; j++){//ith position: elements from i till n-1 candidates
            if(temp2[j] < temp2[i_min]) 
                i_min = j; //update the index of minimum element
        }
        temp = temp2[i];
        temp2[i] = temp2[i_min];
        temp2[i_min] = temp;
        alert(temp); //It shows as needed
        $scope.array2.push(temp2); //Here I am having trouble as it saves the sorted final array (the last one) every time the loop runs, but I want to save the current array on each outer loop execution                       
    }
    return list;

    $scope.selectionSort([3,2,3,4,5,1,2]);
    console.log($scope.array2[0]);
    console.log($scope.array2[1]);
    console.log($scope.array2[2]);
});

Apologies for any language errors.

Answer №1

It appears that the solution you are seeking is not very clear at the moment. It seems like you have a complex issue on your hands, possibly exacerbated by your use of Angular.

If you intend to display the array's state after each step of the outer loop in the selection sort algorithm using console.log, you should place console.log at the end of every iteration.

An area that raises suspicion is:

$scope.array2.push(temp2);

To adhere to my suggestion of logging the array's current state at every loop, this line should be changed to:

$scope.array2 = temp2;

This way, you will update array2 with the latest array state for each iteration and then log it. Adding each state to a bigger array and subsequently logging each item in that array may not be the most efficient approach.

However, I can't say for certain if this addresses the root of your problem.

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

Implementing Maximum Character Limit on Input Text Fields with AngularJS

Is there a way to use AngularJS to set a maximum value for an amount field? If the user enters a value greater than 10, I want to display an error message next to the textbox. However, because the type is set to "text," this validation is not working as e ...

reverting the effects of a javascript animation

I am expanding the size of a carousel on a specific pane by adjusting its height and position. Here is how I achieve this: if(currentPane==2) { $("#carousel").animate({height:320},1000); $("#carousel").animate({top:411},1000); $("#dropShadow") ...

Steps for identifying if the line before in a textarea is blank

Is there a way to identify the structure of individual lines within a textarea? As an example, consider the following contents in my textarea: this is the first line in textarea 1234 this is the second line starting with 1234 this is the fourth line and ...

Exploring the methods of incorporating JavaScript into a Node.js application for extracting information from external webpages through web scraping

I have implemented the Twit API for Node.js and deployed my application on Heroku. My inspiration came from Daniel Shiffman's tutorials which can be found at the following links: and My goal is to create a bot that fetches the title of a random Wiki ...

Are there any risks in combining MVVM [angularjs, knockout.js] with MVC [JSF/spring]?

What are the benefits of combining MVVM models like AngularJS and Knockout.js with MVC frameworks like JSF or Spring? Is it considered best practice to manipulate MVVM objects and variables from within an JSF page? For example, updating a dropdown list ...

Searching through an array of objects in MongoDB can be accomplished by using the appropriate query

Consider the MongoDB collection 'users' with the following document: { _id: 1, name: { first: 'John', last: 'Backus' }, birth: new Date('Dec 03, 1924'), death: new Date('Mar 1 ...

Iterate through a JavaScript array and dynamically populate multiple HTML elements with the values using a loop

I need a way to populate an array with numbers and dynamically insert those values into my HTML code in pairs. For instance, I want the value at array index 1 [0] to be 53498 and appear in both the value attribute and within the <div class="n1" ...

Having trouble accessing the ng-model within ng-repeat in the controller of an AngularJS component

One approach I am considering is to use ng-model="model.ind[$index]" in order to keep track of the active tag. This way, when I click on a tag (specifically the 'a' tag), both the parentIndex and $index will be passed to my controller. Subsequent ...

"Looking to programmatically close a modal in JavaScript that was opened using the 'data-target' attribute? Here's how you can

I have a modal template embedded in the same HTML file as my controller. <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#modalDeleteItem">Delete selected item</button> < ...

The functionality of the Angular directive ngIf is not meeting the desired outcome

We are currently working on transferring data from one component to another using the approach outlined below. We want to display an error message when there is no data available. <div *ngIf="showGlobalError"> <h6>The reporting project d ...

sort options by a different dropdown selection

Currently, I am attempting to utilize the value selected in one dropdown to filter the options displayed in the subsequent dropdown. Both dropdowns are populated with data retrieved from several JSON files (as illustrated below). The objective here is to ...

Monitoring changes in the size of the parent element with an AngularJS directive

Issue I am facing a challenge with a directive that updates the size of an element based on the window size. The directive monitors changes in window dimensions and adjusts the element accordingly. MyApp.directive('resizeTest', ['$window&a ...

"Attempt to create angular fork results in an unsuccessful build

I have recently created a fork of angularJs and I am facing an issue when trying to build it. The build process fails when running grunt package npm -v --> 3.5.2 bower --version --> 1.7.2 I followed the steps provided in the official documentation ...

"Unveiling the power of canvas layers in creating dynamic

Curious about the process of achieving this task. Draw, pause for 1 second. Draw frame 2, pause for 1 second. Draw frame 3, pause for 1 second. Clear animation canvas. I believe the solution involves working on an overlapping canvas to avoid being erased ...

Error alert: Unable to find the specified word

Having trouble writing a word to the database due to an error: ReferenceError: Patikrinta is not defined. Below is my ajax script for sending data to a PHP file, and then the PHP script itself if needed. Haven't found a solution on Stack Overflow. $s ...

Utilize the $scope variable as a JSON object for interacting with the $http service

Is there a way to extract all the data from Angular's scope service without creating an additional object? I am trying to send everything on the scope to a server using $http.post, but it seems that $scope is a circular structure, resulting in "Conver ...

Ways to send the output of a function call to a directive?

I wrote a function in my scope that returns an object. When I try to pass the result of this function to a custom directive, it causes an infinite digest loop (try running the snippet and checking your console). It appears that the objectEquality flag is ...

Using the `useNavigate` function from React Router Dom may trigger a complete reload or re-render of the entire application, resulting

Whenever I attempt to programmatically navigate forward or back using a button click in React Router Dom, the useNavigate() function seems to clear all state, redux, and context and revert everything to its initial state. For example: <IconButton onCli ...

Automatically Importing in VSCode - A Guide to Enabling Full Path Imports for Material-UI

When utilizing the auto import function in VSCode to bring in Material-UI components, it defaults to a named import from the main file: import { Button } from "@material-ui/core" Nevertheless, I prefer the auto import to be a full path import li ...

Is it actually feasible to automate and interact with web elements in a NW.js exe app? I have created a JavaScript script to open and test it

A test case for nw.js can be found in the official NW.js documentation. The original test case is written in Python, but I attempted to recreate it in JavaScript. However, I encountered an error that made it difficult to interact with elements in the nw.ex ...