0

How to sort matrix in AngularJS, I have tried this but it not working:

script.js

function MyCtrl($scope){
    $scope.matrix = [
        [3, 3, 3],
      [4, 4, 4],
      [2, 2, 2]
    ];

function sort(){
    for (var i = 0; i < $scope.matrix.lenght; i++){
    for (var j = 0; i < $scope.matrix.lenght - i; j++){
        if($scope.matrix[i][0] > $scope.matrix[j][0]){
        var temp = [];
        temp = $scope.matrix[i];
        $scope.matrix[i] = $scope.matrix[j];
        $scope.matrix[j] = temp;
      }
    }
  }
}

And my .html file

<div ng-app>
    <div ng-controller="MyCtrl">
       <ul ng-init="sort()">
           <li ng-repeat="line in matrix">
              {{line}}
           </li>
       </ul>
    </div>
</div>

I don`t understand what I am doing wrong

4
  • "It's not working" isn't very descriptive. What are you expecting your code to do, and what is it actually doing? Are you getting errors in your console? Commented Oct 22, 2018 at 15:52
  • Nothing happens, in my opinion this function sort isn`t calling Commented Oct 22, 2018 at 15:53
  • your sort function is not bounded to scope. Write it as $scope.sort = function(){...}, you can initialise it by calling $scope.sort() in your controller (without ng-init) Commented Oct 22, 2018 at 15:56
  • But what if I need to call it when I get my <ul>, how to call inside controller or what do you mean, Aleksey ? Commented Oct 22, 2018 at 16:14

1 Answer 1

1

From what I can see, you want to sort the matrix rows by the first element in each row. Why not just use sort?

let matrix = [
      [3, 3, 3],
      [4, 4, 4],
      [2, 2, 2]
    ];

console.log(matrix.sort((a, b) => a[0] - b[0]));

Sign up to request clarification or add additional context in comments.

2 Comments

But how to call this function correctly in my .html file?
You can store the sorted matrix in a separate variable in the controller (e.g. $scope.sortedMatrix = $scope.matrix.sort((a, b) => a[0] - b[0]). And then in the html, reference this sortedMatrix like ng-repeat="line in sortedMatrix".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.