Tallying items within an array and incorporating them into a new object

After conducting thorough research, I couldn't find a solution to this particular problem on this platform. I'm intentionally avoiding specifics in order to solve it independently.

var arr = ['cat','car','cat','dog','car','dog']

function orgNums(input) {
    var count = 0;
    var obj = {};
    for (var i = 0; i < input.length; i++) {
        if (input[i] === 'cat')
        obj['cat'] = count++;
    }
    return obj;
}

The desired output is {cat:2}, but currently, I am getting {cat:1}

Ultimately, my goal is to have it return {cat:2, car:1, dog:2, gerbil:1}

I attempted to use obj[cat] = ++count and successfully got the expected result. However, upon adding another if statement like

if input[i] === 'dog', obj[dog] = ++count
, the outcome became {cat:2, dog:4}. It seems the count value persists throughout iterations. How can I reset it to zero each time?

EDIT: This new approach works perfectly var arr = ['cat', 'car', 'cat', 'dog', 'car', 'dog']

function orgNums(input) {
    var obj = {};

    for (var i = 0; i < input.length; i++) {
        obj[input[i]] = obj[input[i]] || 0;
        obj[input[i]]++;
    }
    return obj;
}

console.log(orgNums(arr));

However, my actual desired final output is:

[
{cat:1
dog:2
}
{car:2
}
]

Attempting to integrate an if statement like this:

if (input[i] === 'cat'||'dog')

still includes car in the object. I will continue exploring how to handle multiple objects within the array. Thank you once again!

Answer №1

One way to approach this problem is by reducing the array and keeping track of the keys as you iterate through it

var arr = ['lion', 'leopard', 'lion', 'tiger', 'leopard', 'tiger', 'cheetah'];

function countOccurrences(input) {
    return input.reduce((acc, curr) => acc[curr] ? acc[curr]++ : acc[curr] = 1, {});
}

console.log(countOccurrences(arr));

Answer №2

When using the loop, assigning the variable count does not work as expected due to the postfix increment count++. With postfix increment, the current value is returned and then incremented later. To get the incremented value assigned immediately, you should use prefix increment ++count.

// Postfix 
var x = 3;
y = x++; // y = 3, x = 4

// Prefix
var a = 2;
b = ++a; // a = 3, b = 3

Instead of using a separate variable, you can directly count each item using an object property within a loop.

You can set the element as a key in the object and initialize it to zero if it does not exist before incrementing.

var arr = ['cat', 'car', 'cat', 'dog', 'car', 'dog']

function orgNums(input) {
    var obj = {};

    for (var i = 0; i < input.length; i++) {
        obj[input[i]] = obj[input[i]] || 0;
        obj[input[i]]++;
    }
    return obj;
}

console.log(orgNums(arr));

A more concise version can be achieved using Array#forEach

var arr = ['cat', 'car', 'cat', 'dog', 'car', 'dog']

function orgNums(input) {
    var obj = {};

    input.forEach(function (item) {
        obj[item] = (obj[item] || 0) + 1;
    });
    return obj;
}

console.log(orgNums(arr));

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

Error encountered while executing the getCountry method

Seeking some assistance with a code issue. The problem seems to be related to the line of code countries[numCountries]=newCountry;. I am puzzled by the error message indicating a type mismatch that states "cannot convert Country[] to Country". I had assum ...

Easiest method for maintaining data on the server in a persistent manner

(I may not have all the details to ask a specific question, but I am interested in learning more about developing a basic web application using HTML and JavaScript. One idea I have is creating a map where users can add, edit, or remove markers. This would ...

Is there a way to make this variable function properly within the google.maps.LatLng() method?

I've been working on a function that goes through some JSON data and retrieves latlong information to be displayed inside google.maps.LatLng(). The issue I'm facing is that I keep getting a null return and I can't seem to identify the reason ...

What could be causing the data storage issue in the state?

Using axios, I am fetching data and storing it in a state variable useEffect(() => { getCartItems(); }, []); const [abc, setAbc] = useState([]); const getCartItems = async () => { let data = await CartApi.get(`/${store.getState().auth.user.id}/ ...

Transform an asynchronous callback into an asynchronous generator format

I have the following function from a third-party package that I am unable to modify async function runTransaction(callback) { const client = await createClient(); try { await client.query("BEGIN"); await callback(client); } ...

Is nesting ajax calls in jQuery a clever strategy?

I currently have this ajax call: $.ajax({ url: "misc/sendPM.php", type: "POST", data: data, success: function(stuff) { if (typeof stuff == "object") { var err = confirm(stuff.error); if (err) { ...

I want to customize my Google Apps Script to only target specific cells, not all cells

I need help with a script that changes the currency symbol within specific cells based on user selection. Currently, the script is applied to all cells but I only want it to affect cells C9, C12, and C13. I'm not sure where to make this adjustment in ...

drawImage - Maintain scale while resizing

I am currently working on resizing an image using drawImage while maintaining the scale. Here is what I have so far... window.onload = function() { var c = document.getElementById("myCanvas"); var ctx = c.getContext(" ...

Using AJAX in Laravel Blade to bypass the specified div class

As a beginner in AJAX JavaScript, I have been trying to filter data in Laravel 10 without refreshing the page using AJAX, but so far I haven't had much success. Below is the code snippet from my blade view: <script src="https://code.jquery.co ...

Utilize the toggle feature by retrieving the dynamic ID from ng-repeat within the scope

Hey there! I'm currently working on a UI that contains multiple links, and when clicked, each link should toggle to display different data. The challenge I'm facing is that the data is being generated dynamically using ng-repeat. How can I ensure ...

Execute ReactJS function only if query parameters are configured

Provide an Explanation: Within the useEffect, I am retrieving products using the getProducts() function based on the provided data. The data contains search filters that can be updated by the user in real-time. For instance, the data consists of an object ...

Transforming the appearance of the menu element in Vue using transitions

In my Vue app, I have this SCSS code that I'm using to create a smooth transition effect from the left for a menu when the isVisible property is set to true. However, I am encountering an issue where the transition defined does not apply and the menu ...

Combining two sets of data in Python to create a JSON object for an AJAX response

Currently, I am in the process of developing a script that utilizes 2 database queries through ajax. Here is an excerpt from the code: if(request.args.get('staff')): data = [] sel = select('*').select_from(staff).where(staff.c. ...

Locating the indexes of several arrays that meet a criteria in MATLAB

I currently have three large arrays labeled as DataArray1, DataArray2 and DataArray3. All three arrays are the same size, with dimensions of 7000000x1. My goal is to identify the indices in these arrays that meet a specific condition using the find functi ...

Unable to write to file due to permission restrictions from EPERM. Will delete existing file and create a new one. This action

I am encountering an issue with my file system function that involves deleting a file and creating a new one with updated data. The error occurs randomly, not consistently, happening approximately every other time the code runs. Below is my current impleme ...

Create folders and .js files with ease using command line automation

In my React app project, I find myself repeatedly copying and pasting three specific files to a new directory whenever I create a new component. These files include import statements at the top and a class declaration within the body. Is there any way for ...

When a decimal of 0.02 is added to a number in javascript, it may lead to

I am attempting to create an array of numbers ranging from a specific minimum value to a certain maximum value with a specified decimal interval, such as 0.02. For instance, the sequence would be like: 1.00, 1.02, 1.04, 1.06 The issue arises when the code ...

The React forwardRef Higher Order Component is failing to provide a reference to the container element

I'm currently working on creating a higher order component (HOC) for closing an element when clicked outside of its space, known as a generic close on outside solution. In my understanding, this can be achieved using forwardRef and HOC implementation ...

Understanding the behavior of invoking higher order functions can be quite perplexing

I'm encountering an issue with invoking a function within another function. I can't figure out why I am unable to invoke a function using the following logic: function func1(futurefunc){ futurefunc(); } function func2(){ return 3+3; } func ...

How to handle a situation where a React child component is blocking the

My child is currently preventing the parent method from being called when onMouseOver occurs. In order to gain a better understanding of the issue, I am including a code snippet and explaining what my desired outcome is. renderDropdown(){ let dropSt ...