0

I have a custom directive that is holding an array of JavaScript objects.

The object is a little complex and lengthy but I will display something similar to point out my problem:

A JSON.stringify of this displays the following:

[
  {
    "Id": 1,
    "Name": "John Doe",
    "EMail": "[email protected]"
  },
  {
    "Id": 2,
    "Name": "Jim Doe",
    "EMail": "[email protected]"
  },
  {
    "Id": 3,
    "Name": "Jeff Doe",
    "EMail": "[email protected]"
  }
]

I am further using ng-repeat to display the values in a tabular form on my HTML.

The values are coming from an API call that fetches them from a database.

I want to swap - say the entire Object with Id 1 with the entire Object with Id 3 so that during my tabular display I can see Id 3 object details first and Id 1 object details last, without breaking any functionality.

What would be the best possible solution to do this within the frontend itself?

2 Answers 2

1

How about just swapping them using a temp variable?

var arr = [{"Id":1,"Name":"John Doe","EMail":"[email protected]"},
 {"Id":2,"Name":"Jim Doe","EMail":"[email protected]"},
 {"Id":3,"Name":"Jeff Doe","EMail":"[email protected]"}]
 var tmpObj = arr[0];
 arr[0] = arr[2];
 arr[2] = tmpObj;
Sign up to request clarification or add additional context in comments.

4 Comments

I'm running a for loop since the number of objects is large, what would be the best way to switch it within the loop?
just save indexes of elements you need to swap within the loop (by checking ids or names or whatever you need), and then swap them after the loop as I showed above
jsfiddle.net/3mL70v4q/2 This is what I tried, it doesn't seem to be swapping anything though, what am I missing ?
you need to save indexes, not the elements, see updated fiddle
0

If you want to reverse the array, use Array.prototype.reverse()

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

app.controller("myController", function($scope) {
  var arr = [
    {
      "Id": 1,
      "Name": "John Doe",
      "EMail": "[email protected]"
    },
    {
      "Id": 2,
      "Name": "Jim Doe",
      "EMail": "[email protected]"
    },
    {
      "Id": 3,
      "Name": "Jeff Doe",
      "EMail": "[email protected]"
    }
  ];
  
  $scope.array = arr.reverse();

});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.min.js"></script>

<div ng-app="myApp">
  <div ng-controller="myController">
    <div ng-repeat="item in array">
      {{item.Id}} - {{item.Name}} - {{item.EMail}}
    </div>
  </div>
</div>

1 Comment

Nope it isn't reversing - it's more like swapping them based on indexes

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.