How can I attach the index of a duplicate number within an array as a property of that array?

I have an array containing different types of vehicles like [{type: car}, {type: van}, {type: truck}, {type: car}]

My goal is to transform this array into one that includes a count for each type, like so: [{type: car, count: 1}, {type: van, count: 1}, {type: truck, count: 1}, {type: car, count: 2}]

In the final array, there should be a new property that indicates how many times each type appears in the original array.

This modification is needed because I will be rendering the array and want to display a number next to values that are duplicated. I am considering using array methods such as reduce and map, possibly even incorporating a find function.

The main difference between my question and a related link is that while the linked answer returns an array with unique values and their duplicate counts, I want to retain the original array structure but add a property indicating the occurrence number of each value.

So far, I attempted to use a reduce function to calculate the duplicates count for each value, but when mapping through the original array, I struggle to determine whether it's the first or subsequent instance of that value. For example, detecting if the current value has occurred multiple times without knowing its order within the array.

Here is what I have tried:

let countArray = this.props.clauses.reduce((prev, cur) => {prev[cur.leaseClauseType] = (prev[cur.leaseClauseType] || 0) + 1; return prev; }, {});

this.props.clauses.map((c: AnyObject, index: number)=> {
// Here I can attach the count from countArray to each value, however, I aim to distinguish whether it's the initial or subsequent appearance of that value.
}

Answer №1

If you're looking to efficiently achieve this task, consider implementing a solution that utilizes two loops:

const updateCountProperty = function (elements) {
  // Create an object to keep track of the count for each type
  const typeCountMap = {};
  
  for (let i = 0; i < elements.length; i++) {
    const currentElement = elements[i];
    
    if (typeCountMap[currentElement.type] === undefined)
      typeCountMap[currentElement.type] = 0;
    
    typeCountMap[currentElement.type] += 1;
  }
  
  // Set the 'count' property for each element in the array
  for (let i = 0; i < elements.length; i++) {
    const currentElement = elements[i];
    currentElement.count = typeCountMap[currentElement.type];
  }
  
  return elements;
};

Answer №2

If you're looking to keep track of counts, consider using a Map in JavaScript.

var data = [{ type: 'car' }, { type: 'van' }, { type: 'truck' }, { type: 'car' }],
    result = Array.from(
        data.reduce((m, { type }) => m.set(type, (m.get(type) || 0) + 1), new Map),
        ([type, count]) => ({ type, count })
    );

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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 steps can I take to minimize the flashing of this fixed navigation bar?

My fixed navigation bar fades out when scrolling down the page and reappears when scrolling up, which all works well. However, I have noticed that if I do this very quickly with short movements, around 20 times, it doesn't have enough time to complete ...

Calculating the distance of a child element from the top-left corner of its parent element in JavaScript

Can you determine the offset of a ChildElement in relation to a specific parent element? For instance, if a DIV is nested inside a parent DIV with the ID "xyz" Is there a method to achieve this using jQuery? let parent = $("#xyz"); let child = $("#abc") ...

When an external image is dragged over, include the class in the drop area of the file input

Hey, does anyone know how to use Jquery to add a class when an element is being dragged over a drop area? Here's the HTML code I'm working with: <div class="upload"> <form action=""> <input class="uploadfile" type="file" ...

Integrating Contact Form with PhoneGap API using JavaScript and HTML5

I am currently working on building a contact form using the PhoneGap API integrated with JavaScript and HTML5 for the form design. The contact form I am creating should allow me to add new contacts and search for existing ones. To achieve this, I have been ...

What is the process of exporting ES6 from main.js in Vue.js 2.0?

I've encountered an issue while using the webpack-simple-2.0 template for Vue.js (version 2.0.0-beta.5). When I include export const FOO='bar' in my main.js file, I'm unable to successfully import { FOO } in another .js file - it alway ...

What is the best way to transfer a variable from a node server to a javascript client when the page is first

My web application is mainly static, but I need to dynamically send the user's username if they are logged in and the room name they specify in the URL to the client-side JavaScript upon page load. Finding a simple solution has been challenging for me ...

Discover the smallest and largest values within the multi-layered object

My JavaScript object is deeply nested with an infinite number of children, each containing a value. var object = { value: 1, children: { value: 10, children:{ value: 2, children: {...} } } } I've tried ...

"Mastering the art of linking AJAX calls in Angular

I need to make 2 AJAX calls, with the second call dependent on the result of the first one. Currently, I am handling it in this way: Service.getA(car).then(function(carInfo) { if (carInfo.success) { Service.getB(carInfo.number).then(function(h ...

Modify the indicator color of the tabs in Material UI v5

https://i.sstatic.net/nhXHL.png I have implemented tabs in my project, but I am unable to change the background indicator: const theme = createTheme({ MuiTabs: { root: { styleOverrides: { indicator: {backgroundColor: "red !i ...

Angular2 allows you to create pipes that can filter multiple values from JSON data

My program deals with an array of nested json objects that are structured as follows: [{name: {en:'apple',it:'mela'}},{name:{en:'coffee',it:'caffè'}}] I am looking to implement a pipe that can filter out objects b ...

CSS translation animation fails to execute successfully if the parent element is visible

Inquiries similar to this and this have been explored, but do not provide a solution for this particular scenario. The objective is to smoothly slide a menu onto the screen using CSS translation when its parent is displayed. However, the current issue is ...

Is it possible to dynamically modify the fetch URL for getServerSideProps using an onClick event?

I'm struggling to find a solution to changing the fetch URL. Specifically, I want to update my let page and refresh getServerSideProps to re-render all News by clicking a button. Is there a way to accomplish this, or should I explore alternative metho ...

Tips for implementing owl carousel in Nuxt.REACT_UNITS_CODIFY

Is there a way to make the script function on every page without the need for these pages to be reloaded? I have the Owl Carousel script in my static folder, and I have already included it in nuxt.config.js as shown below: head: { title: 'title&ap ...

Is there a way to confirm that a file has been successfully downloaded through JavaScript?

Looking for a way to confirm if a file has been successfully downloaded using JavaScript. Our project utilizes frameworks such as Selenium, Cucumber, and Nightwatch. I have come across some solutions in C, but they do not seem to be suitable for my projec ...

Having trouble getting the jQuery function to update text properly

I'm curious to understand the behavior happening in this code snippet. It seems like updating the list item by clicking doesn't work as expected using the initial method. But when rearranging the JavaScript code, it displays the correct value wit ...

How to message someone privately in a public Discord channel using discord.js

Can someone help me figure out how to create a message in discord.js version 12.5.3 that only I can see? I know how to send messages to channels using message.channel.send, but I'm not sure how to make a message visible only to myself. Thank you! ...

Is it considered poor practice to employ setTimeout to ensure that a function is executed after the useEffect hook has run?

Let's imagine I have the following code snippet: const [test, setTest] = useState(); const [test2, setTest2] = useState(); useEffect(() => { setTest2(undefined); }, [test]); const calledFunction => () { setTest(whatever); setTest2(this ...

The jQuery ajax function is failing to return any results

Here is the code snippet I am working with: $("#MainContent_btnSave").click(function () { if (($("#MainContent_txtFunc").val() == "") || ($("#MainContent_cmbLoc").val() == "")) { alert("Please make sure to fill in all required ...

How to create an Angular 2 template HTML loop to check for true or false in an

For example: Here is a sample Object: { "Person": { "Name": {}, "Hobbies": { "0": { "Description:Soccer": {}, "IsActive:false": {} }, "1": { "Description:Hockey": {}, "IsActive:false": {} ...

The art of efficiently handling and outputting an array of files using node

In a folder filled with markdown files like so: myDir |- fileA.md |- fileB.md |- fileC.md |- fileD.md I want to extract just the filenames without the file extension and store them in an array. This is my attempt: var mdFiles = fs.readdir('myDir&a ...