Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get index position of an array item in controller passing a value in angularjs

I have an array with list of values.

 [Object { id="5", country="UAE"}, Object { id="4", country="India"}]

I want to get the index of array item based on the value present in the id. How can I get the index position of an array item with value of id = 4 in angularJS Controller?

like image 928
uma Avatar asked Jun 17 '14 11:06

uma


4 Answers

Pass the id that you want to remove from the array to the given function from the controller (function can be in the same controller but prefer to keep it in a service).

  function removeInfo(id) {
    let item = Object .filter(function(item) {
      return Object.id === id;
    })[0];
    let index = Object.indexOf(item);
  }
like image 150
Utkarsh Joshi Avatar answered Oct 20 '22 02:10

Utkarsh Joshi


The angularjs way (using $filter) would be something like this

app.controller('MainCtrl', ['$scope', '$filter', function($scope, $filter) {

    //array
    var items = [{  id: "5", country: "UAE" }, { id: "4",  country: "India" }];

    //search value
    var id2Search = "4";

    //filter the array
    var foundItem = $filter('filter')(items, { id: id2Search  }, true)[0];

    //get the index
    var index = items.indexOf(foundItem );
}]);
like image 29
jingel Avatar answered Oct 20 '22 00:10

jingel


this is not angularjs specific problem but normal javascript. just loop and return the index

var list =  [{ id="5", country="UAE"}, { id="4", country="India"}];

for (var i = 0; i < list.length ; i++) {
        if (list[i][id] === 4) {
            return i;
        }
 }

you can then make it generic by making it function on array which accepts the value and property name

Array.prototype.getIndexOfObject = function(prop, value){
   for (var i = 0; i < this.length ; i++) {
            if (this[i][prop] === value) {
                return i;
            }
     }
}
like image 10
Anand Avatar answered Oct 20 '22 01:10

Anand


You can use the map() function to iterate over each object in your array and inspect any desired property. For example if you have an array of objects

$scope.items = 
[
{'id':'1','name':'item1'},
{'id':'2','name':'item2'}
];

to get the index of the second object in the array use

var index = $scope.items.map(function (item) {
            return item.id;
        }).indexOf(2);

returns the index of the object containing the value of 2 in the id property.

like image 3
Akinwale Avatar answered Oct 20 '22 00:10

Akinwale