Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add an element of array to another object and count number

Firstly, I have an array with object element like below:

$scope.selectedIngredient = [object1, object2, object3, object1, object2];

secondly , I have a new object :

$scope.selectedIngredientResults = {};

Now I wanna achieve one function in javascript like this:

count each object element of array and put them into a new object and store each

count

$scope.selectedIngredientResults = [

    {"object" : object1, "count" : 2},
    {"object" : object2, "count" : 2},
    {"object" : object3, "count" : 1}

];

here is array with object elements

[![here is new object result, this is what I want,

I was trying 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 ); 
        }
    }

}
like image 379
Agnes Avatar asked Dec 02 '25 10:12

Agnes


1 Answers

first you need to apply group by by your key. then extract the result from the grouping. here is a transform function what you would need.

function transform(items) {
    items = items.reduce(function (memo, val) {
        var key = val['ingredient_id'];
        if (!memo[key]) {
            memo[key] = [];
        }
        memo[key].push(val);

        return memo;
    }, {});

    var result = [];
    for (var k in items) {
        var groups = items[k];
        result.push({ 'object': groups[0], 'count': groups.length });
    }

    return result;
}
like image 97
Sufian Saory Avatar answered Dec 04 '25 23:12

Sufian Saory