Initially, my array contains object elements as shown below:
$scope.selectedIngredient = [object1, object2, object3, object1, object2];
Next, I have a new object :
$scope.selectedIngredientResults = {};
Now, I want to create a JavaScript function that does the following:
Count each object element in the array and store them in a new object along with their counts.
$scope.selectedIngredientResults = [
{"object" : object1, "count" : 2},
{"object" : object2, "count" : 2},
{"object" : object3, "count" : 1}
];
https://i.sstatic.net/N4miS.png
[![Here is the resulting new object that I want,
I attempted to achieve this by using
$scope.addIngredient = function(selectedElement) {
console.log('selectedElement', selectedElement);
$scope.selectedIngredient.push(selectedElement);
console.log('$scope.selectedIngredient' , $scope.selectedIngredient);
$scope.selectedIngredientResults = {};
var lengthofR = $scope.selectedIngredient.length;
for (var i = lengthofR - 1; i >= 0; i--) {
var selected = $scope.selectedIngredient[i]['ingredient_id'];
console.log('lengthofR', lengthofR);
if(selected){
if($scope.selectedIngredientResults.hasOwnProperty(selected)){
$scope.selectedIngredientResults[$scope.selectedIngredient]++;
}else {
$scope.selectedIngredientResults[$scope.selectedIngredient] = 1;
}
console.log('$scope.selectedIngredientResults', $scope.selectedIngredientResults );
}
}
}