edu edu - 2 months ago 15
AngularJS Question

Comparing objects inside array, do i use equals or indexOf -1?


  1. How can i check equality of arrays objects values (lets say, if im trying to add new date and time, which are same as old), when i have array named orderInfo, do i need to use 'indexOf' or 'angular.equals' method?

  2. How i do the checking from array, because these ones pass the if statement?

    $scope.orderInfo = [{date: '11.11.2011', time: 8},
    {date: '11.11.2005', time: 8}];


    if ($scope.orderInfo.indexOf(time) === -1) {

    $scope.orderInfo.push({date: pvmr, time: aikas});

    $scope.errortextt = "info added";


    } else {
    $scope.errortextt = "already on list";
    }



or

$scope.containsObject = function (orderInfo, time) {
var i;
for (i = 0; i < orderInfo.length; i++) {
if (angular.equals(orderInfo[i], time)) {


$scope.errortextt = "already on list";
return true;
}
}
$scope.orderInfo.push({date: pvmr, time: aikas});

$scope.errortextt = "info added";
return false;
};

Answer

indexOf will only work if it's an array of numbers or strings not objects unless you are actually giving it a reference to an object that is in the array (not one with the same values). The angular.equals function will check the equality of the properties of the object individually to determine if they are "equal".

Personally think the best way to solve this particular problem is to just use another object as a "hash map" to determine if you have the value or not, this way no need to loop or do the deep comparison, the only difficulty is in coming up with your unique "key" for storing/checking a value for example:

var orderInfoIndex = {};
$scope.containsObject = function (orderInfo, time) {
  if (orderInfoIndex[time.toString()]) {
    $scope.errortextt = "already on list";
    return true;
  }

  orderInfoIndex[time.toString()] = true;

  $scope.orderInfo.push({date: pvmr, time: aikas});

  $scope.errortextt = "info added";
  return false;
};