"Switching out elements and tallying up values in an array

I am working with an array of identifiers for items

 var names = ['1','2', '1', '3'];

Using these ids, I send an ajax request to retrieve the name associated with each id and replace it accordingly;

 var names = ['ham','cheese', 'ham', 'onion'];

Ultimately, I want to display a list like this:

 ham x2, cheese, onion

But instead, I end up with:

 ham x2, cheese, ham, onion

How can I achieve the desired result?

Here is my code:

var list = [];

function _checkIngredients(pizza, ingredient) {
    for (var i = 0; i < list[pizza].ingredients.length; ++i) {
        if (list[pizza].ingredients[i] == ingredient) {
            return true;
        }
    }
    return null;
}

pizzas.get().then(function (response) {
    list = response.data;
    angular.forEach(list, function (v, k) {
        // Find ingredient names per pizza
        angular.forEach(v.ingredients, function (i, ik) {
            ingPerPizza.get(i).then(function (response) {
                var name = response.data.name;
                if (_checkIngredients(k, name)) {
                    list[k].ingredients[ik] = '2x' + name;
                } else {
                    list[k].ingredients[ik] = name;
                }
            });
        });
    });

Thank you!

Answer №1

If I were to handle this situation, I would opt for utilizing an external library such as lodash or underscore. The countBy function within these libraries is particularly efficient:

let items = ['apple', 'orange', 'apple', 'banana'];
$scope.finalResult = _.countBy(items);

The resulting output will be:

{
  "apple": 2,
  "orange": 1,
  "banana": 1
}

You can then display the information like this:

<div ng-repeat="(key,value) in finalResult">{{key}} x{{value}}</div>

Answer №2

To efficiently organize all ingredients, store them in an array and then use underscore's (http://underscorejs.org/#) _.groupBy function to group them by name.

pizzas.get().then(function (response) {
    list = response.data;
    angular.forEach(list, function (v, k) {
        //Find ingredients names per pizza

        var ingredients = [];
        angular.forEach(v.ingredients, function (i, ik) {
            ingPerPizza.get(i).then(function (response) {
                ingredients.push({name: response});
            }
        });
        ingredients = _.groupBy(ingredients,'name');
        //do something what you want with this object and attach to pizza       
    });
});

After grouping, the structure of `ingredients` would look like:

{
  "ham": [
    {
      "name": "ham"
    },
    {
      "name": "ham"
    }
  ],
  "cheese": [
    {
      "name": "cheese"
    }
  ],
  "onion": [
    {
      "name": "onion"
    }
  ]

You can easily determine the quantity of each ingredient using ingredients['cheese'].length.

Displaying the quantities can be done simply as follows:

<div ng-repeat="(key,data) in ingredients">{{key}} x {{data.length}}</div>

http://jsfiddle.net/aartek/7gfs27zz/

Answer №3

An interesting way to enhance the functionality of Array and Object is by extending their natives. By doing this, you can create a custom method that will give you a result like: ["ham: 2", "cheese: 1", "onion: 1"].

     
var names = ['ham','cheese', 'ham', 'onion'];

Array.prototype.compileObj = function() {

    var instances = {};

    this.forEach(function(element, index) { 

        if (instances[element]) {
            instances[element] += 1
        }

        else { 
            instances[element] = 1;
        }
    });

    return instances
}

Object.prototype.toArr = function() {

    var returnArr = [],
        obj = this;

    Object.keys(obj).forEach(function(element, index) {

        returnArr.push(element + ': ' + obj[element]);

    });

    return returnArr;
}

console.log(names.compileObj().toArr())

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

What is the best way to include basic static files and HTML together in a NodeJS environment?

I am facing an issue trying to serve an HTML file with its CSS and JS files in NodeJS using express.static(), but unfortunately, it is not working as expected. I have followed the steps shown in several tutorials, but for some reason, the output is not co ...

JavaScript allows for the manipulation of elements within a webpage, which includes accessing elements from one

There is a file that contains a fragment for the navbar. The idea is to have listItems in the navbar, and upon clicking on those listItems, another subnavigationbar should open below it. Below is the code I currently have: <!DOCTYPE html> <html x ...

jQuery cannot access a hidden CSS property

I'm working on a form for my new project and have assigned the same class to all input fields. In my CSS file, I've set the text to be capitalized and it displays correctly. However, when I use jQuery's .val() to get the value of the field, ...

Issue encountered: "require" is not recognized when attempting to access my local JSON file in Vue.js

I am venturing into the world of vuejs... I attempted to retrieve data from my JSON file stored locally, but the decision on which specific JSON file's data to fetch is dynamic. I keep encountering an error stating 'require' is not define ...

Increase the object name in localStorage to save information entered in input fields

For testing purposes only - do not use for production. I am experimenting with storing data from 3 different input fields (text and numbers) in localStorage. My goal is to have the values increment every time the form is submitted. However, I am encounte ...

Guide to generating a new element and displaying updated data whenever it is retrieved in a React application

I'm completely new to React and I'm struggling with rendering and listing data fetched from Firebase on my HTML page. I attempted the following approach: const Music = ({ match }) => { const [titles, setTitles] = useState([]); // Change ...

Passing null as a parameter in ngResource AngularJS

I am currently utilizing ngResource from AngularJS 1.2.1, and I'm encountering an issue when attempting to include null as a parameter value in a PUT request. It seems that Angular ignores the parameter entirely and does not send it along with the req ...

Using Alpine JS to rotate through images at regular intervals using the window.setInterval() method

Attempting to tackle a simple task using Alpine JS and the standard JS function setInterval. The goal is to create an image selector where images switch every second (1000ms). Here's what I have so far: <div x-data="imgFunc()"> ...

Activating list anchor upon click

I have a list that looks like this: <!-- List --> <ul class="nav nav-sm nav-tabs nav-vertical mb-4 steps-sampling"> <li class="nav-item"> <a class="nav-link active" id="link1" href="{{ ...

Image not showing up on HTML page following navigation integration

Having trouble with my responsive website setup - the background image for ".hero-image" isn't showing up after adding the navigation. Google Chrome console is throwing a "Failed to load resource: the server responded with a status of 404 (Not Found)" ...

Validation of forms in AngularJS/HTML5 that are nested within one another

Just starting out with AngularJS and experiencing issues with HTML5 nested form validation. I currently have 2 forms; mainFrm (parent form) and stateFrm (a child form). I am struggling to validate each form within its own scope. <form id="mainFrm" ng- ...

unable to toggle the navbar

Currently, I am facing an issue with the navbar-toggle button while using Bootstrap. Initially, I thought the problem was with my navbar code, so I tried pasting the example from the Bootstrap Website, but it did not work either. The button appears, but t ...

Deploying CSS/JS files in Magento 2 is a crucial

Hello, I recently set up magento2 with the sample data included. After attempting to deploy static css/JS using the command php bin/magento setup:static-content:deploy, I didn't receive any errors but the issue persists. Additionally, I am unable to l ...

Angular Bootstrap Collapseable Panel

In my search for a non-javascript solution combining angular and bootstrap to create collapsible columns, I couldn't find any existing solutions. So, here's the method I devised to achieve this functionality on my own. ...

Managing dynamically appearing elements in Ember: Executing a Javascript function on them

I'm currently working on a project in Ember and facing an issue with calling a JavaScript function when new HTML tags are inserted into the DOM after clicking a button. Below is a snippet of my code: <script type="text/x-handlebars" id="doc"&g ...

Please ensure to refresh the page after confirming the alert box by clicking OK

Is it possible to clear certain inputs on my Magento store's checkout page when an alert box is displayed and the user clicks OK? Unfortunately, I do not have control over the JavaScript alert. Therefore, I thought of implementing a script that can d ...

Tips for utilizing the @run-at document-start meta-rule

Currently, I am utilizing the following code snippet: Jquery(window).load(function(){ // here is my code for making an AJAX request to retrieve data from the database }); Unfortunately, I have encountered an issue specifically with its function ...

Conceal overflow content within a Bootstrap btn-group using CSS styling

Suppose I have a table like the one below: /* CSS Styles for the table */ table.my { width: 600px; } table.my > tr { height: 40px; overflow: hidden; } .tag { background: #b8b8b8; padding ...

Illustrate an element positioned beneath a child element within a different element

I am in the process of designing an overlay on a Google Map that resembles a real map placed on a table, using 2 pixel lines as creases above the map. This design does not significantly impact interactions with the map; only 6 out of 500 vertical lines are ...

React 16 is encountering a discrepancy due to the absence of the data-reactroot attribute

As I was in the midst of updating some apps to React 16, I couldn't help but notice that the data-reactroot attribute is no longer present on the main root element. Although not a critical issue, it seems like we had certain code and styles that reli ...