AngularJS: How to check if value exists in array of objects?
<p>I'm trying to write a function that iterates through an array of objects, and pushes in new ones (ones that have a unique name), while updating ones that have already been seen.</p>

<p>Say for example, I have this array:</p>

<pre><code>$scope.myArray = [
    { "name": "Apple", "total": 16, "applicable": 21 },
    { "name": "Cherry", "total": 12, "applicable": 27 },
    { "name": "Plum", "total": 14, "applicable": 21 },
    { "name": "Apple", "total": 16, "applicable": 21 },
    { "name": "Cherry", "total": 12, "applicable": 27 },
    { "name": "Plum", "total": 14, "applicable": 21 },
    { "name": "Banana", "total": 14, "applicable": 21 },
];
</code></pre>

<p>By the end of the function, the new array should be:</p>

<pre><code>$scope.myNewArray = [
    { "name": "Apple", "total": 32, "applicable": 42},
    { "name": "Cherry", "total": 24, "applicable": 54},
    { "name": "Plum", "total": 28, "applicable": 42},
    { "name": "Banana", "total": 14, "applicable": 21 },
];
</code></pre>

<p><strong>Here's what I have so far:</strong></p>

<pre><code>$scope.myArray = [
    { "name": "Apple", "total": 16, "applicable": 21 },
    { "name": "Cherry", "total": 12, "applicable": 27 },
    { "name": "Plum", "total": 14, "applicable": 21 },
    { "name": "Apple", "total": 16, "applicable": 21 },
    { "name": "Cherry", "total": 12, "applicable": 27 },
    { "name": "Plum", "total": 14, "applicable": 21 },
    { "name": "Banana", "total": 14, "applicable": 21 },
];

$scope.myNewArray = [];

$scope.myArray.filter( function () {

    var i = $scope.myNewArray.indexOf($scope.myArray.name);

    if ($scope.myNewArray.indexOf($scope.myArray.name) &lt; 0)
        $scope.myNewArray.push($scope.myArray);

    else {
        $scope.myNewArray[i].total += $scope.myArray.total;
        $scope.myNewArray[i].applicable += $scope.myArray.applicable;
    }
});
</code></pre>

<p>The problem I'm encountering is everything gets pushed into the new array. That and I believe my else statement where I'm adding the values to the previous record might be wrong.</p>

<p>Also, hard-coding an array for each name doesn't work as this is just a simple example with a small dataset.</p>

<p>Can anyone lend a hand?</p>