Guide to tallying the occurrences of a specific key within an object array and attaching the count to each key's current value

Is there a way to determine the number of occurrences of the 'value' key within an object that is part of an array, and then add the count to each value if applicable?

In this case, 'a' represents the original data

var a = [
    { id: 1, value: "10000"},
    { id: 2, value: "20000"},
    { id: 3, value: "30000"},
    { id: 4, value: "10000"},
    { id: 5, value: "20000"},
    { id: 6, value: "40000"},
    { id: 7, value: "10000"},
    { id: 8, value: "70000"}
]

The desired outcome is as follows:

result = [
    { id: 1, value: "10000"},
    { id: 2, value: "20000"},
    { id: 3, value: "30000"},
    { id: 4, value: "10000 (1)"},
    { id: 5, value: "20000 (1)"},
    { id: 6, value: "40000"},
    { id: 7, value: "10000 (2)"},
    { id: 8, value: "10000 (3)"}
]

Answer №1

Utilizing Array.map to iterate through the array and store the values.

In my opinion, this approach enhances readability compared to using Map.

const values = {},
  b = a.map(({ id, value }) => {
    values[value] = (values[value] || 0) + 1; // assigning and incrementing
    if (values[value] > 1) value += ` (${values[value]-1})`;
    return { id, value };
  });

console.log(b)
<script>
var a = [
    { id: 1, value: "10000"},
    { id: 2, value: "20000"},
    { id: 3, value: "30000"},
    { id: 4, value: "10000"},
    { id: 5, value: "20000"},
    { id: 6, value: "40000"},
    { id: 7, value: "10000"},
    { id: 8, value: "10000"}
]</script>

Answer №2

Utilizing the Map object can be helpful in keeping track of the number of occurrences for each value.

const data = [
    { id: 1, value: '10000' },
    { id: 2, value: '20000' },
    { id: 3, value: '30000' },
    { id: 4, value: '10000' },
    { id: 5, value: '20000' },
    { id: 6, value: '40000' },
    { id: 7, value: '10000' },
    { id: 8, value: '70000' },
];

const valueMap = new Map();

const processedData = data.map((item) => {
    const count = valueMap.get(item.value);
    valueMap.set(item.value, (count ?? 0) + 1);
    return count ? { ...item, value: `${item.value} (${count})` } : item;
});

console.log(processedData);

Answer №3

var b = [
    { code: 1, amount: '10000' },
    { code: 2, amount: '20000' },
    { code: 3, amount: '30000' },
    { code: 4, amount: '10000' },
    { code: 5, amount: '20000' },
    { code: 6, amount: '40000' },
    { code: 7, amount: '10000' },
    { code: 8, amount: '10000' },
];

const valueMap = {};

const newArr = b.map((item) => {
    const tempVal = { ...item };
    if (!valueMap[item.amount]) {
        valueMap[item.amount] = 1;
    } else if (valueMap[item.amount]) {
        tempVal.amount = `${item.amount} (${valueMap[item.amount]})`;
        valueMap[item.amount] += 1;
    }
    return tempVal;
});

console.log(newArr);

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

Is there a foolproof way to determine when a dialogue box pops up on

I'm currently building an electron app using vue and Vuetify. I am able to create a modal using dialog, but I want to be able to modify certain elements within the dialog after it is displayed. When using $refs, I cannot find the element before the d ...

Get a list of images by incorporating NextJs and Strapi to create a dynamic slider feature

[] I need help creating a slider as I am encountering an error when trying to output an array of objects. The error can be seen here: . Can someone assist me in resolving this issue? Thank you. Here is a screenshot from the admin panel: 1 Below is the c ...

What is the best way to set the width of a w2grid to 100%

Has anyone tried using w2grid before? I'm having trouble figuring out how to make it fill its container 100%. Here's the HTML snippet: <div id="a" style="width:100%"> <!-- top left container--> <div>This ...

I am unable to generate a vite application within WSL

My system is running node version 10.19.0 and npm version 6.14.4. Whenever I try to run create-vite@latest client, I encounter the following error: npx: installed 1 in 0.79s /home/victor/.npm/_npx/86414/lib/node_modules/create-vite/index.js:3 import &apos ...

Ways to protect my login details when making an ajax request?

The scenario I am dealing with is as follows: I have developed a website using Javascript where users are required to input a username and password. Subsequently, the site makes an ajax call to the Webserver. On the other end, I have a PHP-powered Webser ...

Instructions for rendering a component after directly inserting its tag as raw HTML in Vue 3

Recently, I encountered an issue with a vue instance that contains a globally registered component in a legacy project. Due to the legacy nature of the project, it heavily relies on jsrender for rendering html post ajax requests. Despite having the compon ...

I'm struggling to make the jquery parentsUntil function work properly

Would appreciate some help with using the jquery parentsUntil method to hide a button until a radio box is selected. I've been struggling with this for a few days now and can't seem to figure out what I'm doing wrong. Any insights would be g ...

Create a setup page upon initial login using express.js

Currently, I am implementing Passport.js for user authentication on my express.js application. I aim to display a setup page upon the initial login of the user. Is it possible to achieve this using Passport? ...

Creating a loading screen in Angular2: Step-by-step guide

How can you best integrate a preloader in Angular 2? ...

Check to see if a key exists within the entire JSON using jQuery

I'm struggling with checking if a specific key is contained in my JSON data array. I want to add a class or perform an action if the key is present, otherwise do something else. I've tried using inArray and hasOwnProperty but can't seem to g ...

The Material Icons font family must be loaded via Exponent as it is not a default system font

Currently, I am utilizing the Icon component from react-native-vector icons by importing it with this code: import Icon from 'react-native-vector-icons/MaterialIcons'; It appears that the connection is established correctly. The snippet of cod ...

Limiting User Access on ReactJS Routes

Is there a way to restrict user routes in my application? I want to prevent users from manually typing URLs into the address bar, for example: http://localhost:3000/admin if they are already on https://localhost/users. Only users with admin privileges shou ...

Steps to send a table to PHP and store it as a text file

I have this program for a form data entry. It includes text boxes to input values, and upon clicking 'Submit', the input values should be displayed below while resetting the text box for another set of inputs. The issue I am facing is with the sa ...

Tips for transmitting error messages from Express to React/Redux

I have a MERN app that utilizes Redux for state management. The actions in my app are structured like this: export const logIn = (logInData) => async (dispatch) => { try { const { data } = await api.logIn(logInData); localStorage.setItem(&a ...

Counting Clicks with the Button Counter

I'm having an issue with my jQuery code that is supposed to count button clicks - it stops after just one click. I need help fixing this problem. $(function() { $('.btn').click(function() { $(this).val(this.textContent + 1); }); } ...

Issue with babel-preset-env failing to detect JSX syntax

I'm currently facing an issue while trying to set up a webpack build for the first time. Despite thoroughly reviewing my babel config multiple times in relation to the documentation, I am unable to pinpoint the error causing a problem during the build ...

The Power of jQuery's .ajax() Utility

I'm a beginner with the jQuery AJAX ajax() Method and have recently created the AddATeacher() function. The function gets called successfully as I see all the alert messages popping up. However, the ajax() Method within the function is not working. Th ...

Creating a dynamic collection of N triangles in a container using CSS

In my current project, I am developing an Electron+Vue application that features a grid-styled map. Each cell on the map represents a room, and I want to indicate walls within these cells. Specifically, for directions North, South, East, and West, I can us ...

Issue: Unable to use the b.replace function as it is not recognized (first time encountering this error)

I can't seem to figure out what I'm doing wrong. It feels like such a silly mistake, and I was hoping someone could lend a hand in solving it. Here is my controller - I'm utilizing ng-file-upload, where Upload is sourced from: .controller( ...

Tutorial on Removing and Re-Adding HTML Elements

Currently, I am utilizing Jquery to temporarily remove an element from the DOM. This specific element consists of an HTML5 video element. However, upon re-adding this element back into the DOM, the video is unable to play and the element appears as blank o ...