Input '0' when the value is not present in the array of objects

Hey there! I have an array of objects and I want you to take a look at the code below. Within this array, I have three values: 'A', 'B', and 'C'. If the B value does not exist in Mumbai, I would like to push 0.

Plunker

// Check out the code snippet below

var c = angular.module('myApp', ['angular.filter'])
c.controller('myCtrl', function($scope, $filter) {
    $scope.finalArray = [];

    $scope.data = [{
        "id": "1",
        "place": "Mumbai",
        "name": "A",
        "value": "10"
    }, {
        "id": "4",
        "place": "Mumbai",
        "name": "B",
        "value": "20"
    }, {
        "id": "4",
        "place": "Delhi",
        "name": "B",
        "value": "77"
    }, {
        "id": "5",
        "place": "Delhi",
        "name": "C",
        "value": "11"
    }, {
        "id": "6",
        "place": "Banglore",
        "name": "A",
        "value": "14"
    }, {
        "id": "7",
        "place": "Banglore",
        "name": "C",
        "value": "100"
    },
    {
        "id": "3",
        "place": "Delhi",
        "name": "A",
        "value": "30"
    }]

    $scope.finalArray = [];
    $scope.stationName = [];
    $scope.name = $filter('groupBy')($scope.data, 'name');
    angular.forEach($scope.name, function(k, v) {
        $scope.title = [];
        $scope.count = [];
        console.log(k, v);
        $scope.title.push(v)
        angular.forEach(k, function(key, value) {
            $scope.count.push(key.value)
        })
        var obj = { name: $scope.title[0], data: $scope.count }
        $scope.finalArray.push(obj);
       });
    console.log($scope.finalArray)
})
<!DOCTYPE html>
<html>

  <head>
    <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b1d0dfd6c4ddd0c39fdbc2f1809f869f81">[email protected]</a>" data-semver="1.7.0" src="https://code.angularjs.org/1.7.0/angular.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-filter/0.5.17/angular-filter.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body ng-app="myApp" ng-controller="myCtrl">
    
     {{finalArray | json}}
  </body>

</html>

Currently, the output is as follows:

[ { "name": "A", "data": [ "10", "30", "14" ] }, { "name": "B", "data": [ "20", "77" ] }, { "name": "C", "data": [ "11", "100" ] } ]
However, my desired output should be [{name :"A",data :[10 30 14]},{name : "B",data : [20,77,10]},{name : "C",data : [0,11,100]}]

Answer №1

A custom function called distinct is created to extract unique values from an array. This function is then utilized to generate a list of distinct names and places. Subsequently, the names are mapped into objects within an array where each name corresponds to its associated places.

// Custom code implementation

var c = angular.module('myApp', ['angular.filter'])
c.controller('myCtrl', function($scope, $filter) {
    $scope.finalArray = [];

    // Sample data
    $scope.data = [{
        "id": "1",
        "place": "Mumbai",
        "name": "A",
        "value": "10"
    }, {
        "id": "4",
        "place": "Mumbai",
        "name": "B",
        "value": "20"
    }, 
    ...
    
    const distinct = (array) => array ? array.reduce((arr, item) => (arr.find(i => i === item) ? [...arr] : [...arr, item]), []) : array;
  
    const names = distinct($scope.data.map(obj => obj.name));
    const places = distinct($scope.data.map(obj => obj.place));

    $scope.finalArray = names.map(name => {
      return {
        name: name,
        data: places.map(place => {
          const obj = $scope.data.find(o => o.place === place && o.name === name);
          return obj ? obj.value : 0;
        })
      };
    });
})
<!DOCTYPE html>
<html>

  <head>
    <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="92f3fcf5e7fef3e0bcf8e1d2a3bca5bca2">[email protected]</a>" data-semver="1.7.0" src="https://code.angularjs.org/1.7.0/angular.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-filter/0.5.17/angular-filter.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body ng-app="myApp" ng-controller="myCtrl">
    
     {{finalArray | json}}
  </body>

</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Updating an AngularJS directive's attribute

My unique directive handles validation by the directive attribute value. For example: <input type="text" ng-my-validate="onlyletters" /> I am looking to dynamically change the value from onlyletters to onlynumbers, and I want the directive ...

The behavior of the 'typeof null' function in JavaScript is not functioning

I have a collection of objects where each object contains a key and an array as a value. You can see what I mean in this image. Some of the arrays had less than 20 elements, so I wrote some code to pad them with zeros. The result of running my code can be ...

Can you please explain the significance of (session?._id)?

export default NextAuth({ ... callbacks: { session: async ({ session, token }) => { if (session?.user) { session.user.id = token.uid; } return session; }, jwt: async ({ user, token }) => { if (user) { ...

Unable to retrieve state values or any methods that were declared from renderRow in React-Native

I am facing an issue with my listview. Whenever a user clicks on an item, I want something to happen using onPress (touchable highlight). I attempted to define functions and then call them in onPress, but it didn't work as expected. First, I defined ...

Activate an action only upon closing the page

I am looking for a solution in my vue.js app to execute a function only when the user closes the application. I have tried registering an event listener for beforeunload, but it causes the function to also trigger on page reloads, which is not ideal. Is t ...

What is the best way to access a variable's value from outside a promise?

I encountered an issue while trying to assign a value to a variable outside of a promise. Despite defining the variable outside the promise, it is showing up as undefined when I check its value. Could someone assist me with this problem by reviewing my co ...

Real-time functionality causing issues with Array Push functionality

Utilizing Pusher in an Angular Webapp for Real Time Application. I am looking to automatically add a new product item to the array when another user adds an item from a form in a different session. This functionality works within my own session, however, i ...

Is it possible for me to make the default export anonymous?

Why bother naming the export if you already have a file with the default export name? This seems redundant and goes against the DRY principle. While there is a rule that discourages anonymous default exports, how can we enforce an error when someone does ...

Integrating additional youngsters into the HTML DOM using Angular.js

I am working with a block of HTML that looks like this: <div id="parent"> <div id="child_1"></div> <div id="child_2"></div> <div id="child_3"></div> <div id="child_4"></div> </div> ...

The dimensions of the body are set to 100vh in height and width. However, the div inside this body has a width of either 100vh or 100%, but it is not

I am trying to create a div element that has a width equal to the viewport of the browser. However, I am encountering issues when applying the CSS property width:100vh to the body element. Here is my code snippet: body { font-family: Staatliches; fo ...

What is the most effective method for regularly updating single page applications using PHP/HHVM as the backend?

While working on my single page application using AngularJS, I have come to appreciate the efficiency of creating web applications in this way. My backend language is PHP and the service functions as a REST"ish" API. However, I am currently facing an issu ...

Testing factories with Jasmine and Angular: A step-by-step guide

After conducting thorough research online, I have come up empty-handed in finding a solution to my issue. Essentially, I have a factory declared in the following manner: angular.module('puFactories').factory('RestFactory', function ($h ...

The stored information causes the material ui text fields to malfunction

Having trouble with my text fields in a React and Material UI application. When autofill data is saved, the styling breaks. The component code is included below. I've searched online but couldn't find any helpful solutions. import React, { useSta ...

Utilizing an EJS template within an express.js application to extract and assign data to a variable

Is there a way to transfer data from my node.js (express) app directly to a variable within the <script> tag on the page? On the server-side, I have the following code: let tmp = JSON.stringify(await f(i)); console.log(tmp); //correct data [{"i ...

Jquery is unable to detect duplicate class names

if ($(".event_list")[0]){ if($(".event_list").find(".type").length == 0 && $(".event_list").find(".sold").length == 0) { $(".event_list").click(); } } else { $('#something').click(function() { location.reload(); }); } I attemp ...

Executing controller method through a preflight OPTIONS call for Web API CORS functionality

My angular app is making calls to a WebApi with authentication and sessions enabled, requiring preflight calls for GET and POST methods. I have implemented Cors in the WebApiConfig.vb file. Public Sub Register(config As HttpConfiguration) Dim corsAttr ...

The HTML code is failing to detect the eventListeners

Does anyone know why my JavaScript event listener is not working when I try to link it to my HTML? They are in separate text documents, but I'm not sure if that's the issue. It seems to work with other sections, so there might be a small mistake ...

Show Zeroes in Front of Input Numbers

I am working with two input fields that represent hours and minutes separately. <input type="number" min="0" max="24" step="1" value="00" class="hours"> <input type="number" min="0" max="0.60" step="0.01" value="00" class="minutes"> This se ...

What is the best way to assign JSON objects to distinct global variables in AngularJS?

Currently in the process of learning AngularJS, I have a JSON file containing data that I wish to load into separate variables. The JSON file consists of two objects/arrays: "views" and "addressbook". While I can bind the data to a $scope.variable in the h ...

Is there a way to alter a class using ng-class only when the form is deemed valid?

I am trying to implement a feature where an input field shows as required, but once the user enters text, it indicates that the input is valid by changing the border color from red to green. I am facing an issue with this line of code always returning fal ...