Incorrect way of tallying items in an object and the proper method for tallying similar values between objects and arrays

My attempt was to count the occurrences of the same values in objects and arrays. The goal was to display the initial numbers that appear in arrays within an object. Here is my flawed code along with an example case:

let index = {};
let result = [];
const arrayList = [{
  "code": 101,
  "name": "banana",
  "price": 1000
}, {
  "code": 4,
  "name": "blueberries",
  "price": 3000
}, {
  "code": 900,
  "name": "apple",
  "price": 300
}];

// Array containing user choices
const userChoose = [900, 900, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101];

userChoose.forEach(choice => {
  arrayList.forEach(item => {
    let key = choice;
    if (key in index) {
      index[key].count++;
    } else {
      let newEntry = {
        id: item.code,
        count: 1
      };
      index[key] = newEntry;
      result.push(newEntry);
    }
  })
});
console.log(result);

The output does not match the expected result which should look like this:

// Desired final result:
[
  {
    "id": 900,
    "count": 2
  },
  {
    "id": 101,
    "count": 11
  }
]

Answer №1

It seems like this is the solution you've been searching for.

let index = {};
let result = [];
const arrayList = [{
  "code": 101,
  "name": "banana",
  "price": 1000
}, {
  "code": 4,
  "name": "bluebberries",
  "price": 3000
}, {
  "code": 900,
  "name": "apple",
  "price": 300
}];
 
  // showing the code value in object list
const userChoose = [900, 900, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101];


userChoose.forEach(item => {
  if(result.some(i => i.id === item) === false) {
    let obj = arrayList.find(e => e.id === item);

    result.push({ 
      id: item,
      count: 0
    });
  }
  result.find(r => r.id === item).count++;
});

console.log(result);

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

Ensure that the End Date selected in the Yii Bootstrap datepickerRow comes after the Start Date

Utilizing Yii bootstraps datepickerRow and seeking to have the end_date depend on the start_date. Essentially, the end_date should always be greater than the start_date. After searching extensively online for a built-in solution without success, I decided ...

Performing Select-Object on a PowerShell list without needing to transform the list into an object

Looking to deeply filter a PowerShell Object and convert it to JSON using Select-Object. While Select-Object works well on object properties, it distorts lists. When a list with only 1 element is converted, it becomes an object. When a list has more than ...

React JS - Sending props from Dev and Build to App component

Looking to include static assets and props in my App, specifically having image assets set with a base64 string in the build process. Want to ensure these assets are accessible to the App's props before development and build stages, similar to the fun ...

Minimize a collection of JavaScript objects

I am working with an Array of objects where I need to return the collection as an Object, with the key names being the indexes of their length. Additionally, I have to filter this object based on its values. Check out my code snippet below: const data = ...

Exploring MongoDB: Finding a specific element within an array of words

Is there a way to check if a string contains any of the words from an array? I know how to do it with a single word, but not sure how to do it with an array. Any suggestions? I attempted the following without success: db.getCollection('questions&apos ...

Enhance row visibility by clicking a button in an ajax table

I'm facing an issue where I am trying to apply a highlight class to the selected row in an ajax table when clicking on the edit button, but for some reason my code is not working as expected. Can someone assist me with this problem? Thank you in advan ...

Creating a straightforward HTML output using jQuery and JSON

Currently, I am teaching myself how to handle data flow from mySQL to PHP to JSON/JavaScript, but I seem to be stuck at this particular stage. My goal is to loop through external JSON data and display it in an unordered list. Despite attempting to modify t ...

Ensuring seamless mobile compatibility across all browsers

Functionality: An essential aspect of the web app is its compatibility with all mobile web browsers. This requires the development to be responsive and work seamlessly on various platforms. Steps taken so far: I have made adjustments to the CSS, along w ...

Using Laravel to Toggle Element Visibility Based on Role in VueJS

<NavLink v-if="value":href="route('accounts')" :active="route().current('accounts')"> Accounts Here is a scenario I encountered: within my user database, there are designated roles as either User or ...

Creating an aperture in a form using a different shape in THREE.js

Currently, I am utilizing the D3-threeD2.js library to convert SVG files into THREE.Shape(s) that can be extruded with three.js. The process works smoothly, however, when it comes to incorporating holes, I encounter an issue. Imagine a shape resembling a ...

Leveraging the power of mapState and mapMutations within a namespaced module

I'm having trouble accessing mutations and states after dividing my Vuex store into three modules. I've attempted various syntaxes, but none seem to be working for me. MapStates: This is how I have set up the mapStates, with 'vendor' a ...

What is the method for implementing a Redirect in React Router?

I'm new to React and facing a challenge. My goal is to implement a conditional Redirect, and I have created a function called errorCapture for this purpose. The function should trigger a Redirect based on a specific condition. I have included the ret ...

Using a plain JavaScript React component within a TypeScript React project: A step-by-step guide

A coworker of mine used Typescript for a frontend React project. With their departure, I have been tasked by management to take over the project and deliver results from Day 1. While they are open to me using Javascript in the project, I am unsure how to i ...

Having difficulty modifying the font color on a Select2 dropdown that includes custom attributes

Recently, I have been exploring the integration of Select2 in an older application. I have successfully converted the old dropdown into a Select2 dropdown and everything seems to be functioning properly. The dropdown is populated with options and all relat ...

Tips for preserving a string in angularJS or Java (and implementing it in an iframe)

My plan involves utilizing a Java web service to fetch the HTML content from a specific URL using Jsoup, and then returning it as a string to the requesting party, which could be an Angular or JS script. I am keen on preserving this content somewhere and l ...

Adjusting the dimensions of a shape proportionally as the window size is altered through the onWindowResize() function

After completing some coding courses, I am now venturing into the world of WebGL using Three.js to enhance my programming skills. I have been experimenting with a widely used function in examples on threes.org: function onWindowResize() { ...

What is the reason that PHP has the ability to set Cookies but Local Storage does not?

Let's take a step back to the era of cookies, not too far back since they are considered old but still quite relevant. PHP allows you to set and read them even though they are a client-side technology; however, JavaScript can also be used completely o ...

Learn how to configure your Angular uib-typeahead to display suggestions as soon as the model is bound

Currently, I am setting up a search functionality. Whenever a user inputs a character into the search box, I use the ng-change event to call an API, retrieve the model, and bind it to uib-typeahead. My goal is for uib-typehead to immediately start suggesti ...

The ajax function is malfunctioning when called from an external JavaScript file

I am having an issue with a Registration page that only has UserName and Password fields. When I click on the Submit button, I want to be able to submit the new User Details using an ajax call with jQuery. I have tried defining an Insert function on butt ...

Issues concerning the response type of ASP.net JSON Webservices

Struggling to create an ASP.net web service for a jQuery AJAX call and feeling completely stuck. Despite searching for solutions online, I can't seem to find the right answer. Although my ajax call (via jquery) receives a successful response from the ...