Calculating the number of duplicate elements in an array

I need help with displaying the elements of an array while also counting duplicates. For example:

myArr = ['apple', 'apple', 'orange', 'apple', 'banana', 'orange', 'pineapple']

The output should be:

apple 3
orange 2
banana
pineapple

Currently, I am only able to display them all as a single string:

arrList = myArr.join(', ');
arrList.toString()

Answer №1

The lengthy method

var items = ["apple", "apple", "orange", "apple", "banana"];

items.sort();

var currentElement = null;
var itemCount = 0;

for(var index = 0; index < items.length; index++)
{
    if(items[index] !== currentElement)
  {
    if(itemCount > 0)
    {
        document.write(currentElement + " " + itemCount + "<br/>");
    }
    currentElement = items[index];
    itemCount = 1;
  }
  else
  {
    itemCount++;
  }
}

if(itemCount > 0)
{
    document.write(currentElement + " " + itemCount);

The concise approach

var items = ["apple", "apple", "orange", "apple", "banana"];

var countOccurrences = {};

items.forEach(function(item) {
    countOccurrences[item] = (countOccurrences[item] || 0) + 1;
});

document.write("Apple: " + countOccurrences.apple + "<br/>");
document.write("Banana: " + countOccurrences.banana + "<br/>");
document.write("Orange: " + countOccurrences.orange + "<br/>");

Answer №2

Give this a shot:

const fruits = ['apple', 'apple', 'orange', 'apple', 'banana', 'orange', 'pineapple'];
const fruitCounts = {};
fruits.forEach(fruit => {
  if (typeof fruitCounts[fruit] === 'number') {
    fruitCounts[fruit]++;
  } else {
    fruitCounts[fruit] = 1;
  }
});
document.getElementById('output').innerHTML = Object.keys(fruitCounts).map(fruit => {
  return fruit + (fruitCounts[fruit] === 1 ? '' : ' ' + fruitCounts[fruit]);
}).join('\n');
<pre id="output"></pre>

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

Use Javascript to display specific div elements by clicking a button

I could really use some assistance, When I attempt to display the select div by clicking the button, the "id" that PHP generates returns a null response in the console. The requirement is to only show the div when clicking on the "Quick Quote" button. Pro ...

What could be causing the error "Unexpected identifier 'trytoCatch' while trying to minify?

I recently updated my script.js and now I'm looking to use "minify" in Node.js to compress it. When I type the command minify script.js > script.min.js into the terminal, I get an error message that says: /node_modules/bin/minify.js:3 import "tryTo ...

Error encountered while attempting to define a method in a class component in React.js

Can you tell me if these two code snippets are equivalent? async onSearchSubmit(term) { const response = await axios.get('https://api.somewebsite.com/search/photos', { params: {query: term}, headers:{ ...

Is there a way to make FullPage and Lightbox compatible with each other?

Currently utilizing Fullpage.js for my website, I am looking to incorporate a lightbox in one of the sections. However, upon attempting to load the script and CSS, my fullpage layout breaks and the sections collapse. I have experimented with placing the ...

Automatic Clicks in the Chrome Console

I've come across a website that requires me to click on multiple elements scattered throughout the page Here is the code for one of the elements: <span class="icon icon-arrow-2"></span> Is there a way to provide me with the console comm ...

Is it possible for an Express app.get() function to identify and handle requests for specific file extensions

Is it possible for me to manage requests for any .html file type? For example, can I achieve something like this: // server.js app.get('/*.html', (req, res) => { // perform certain actions when an html file request is made }); ...

What is the best way to obtain a date in the format of yyyy_mm_dd from a datepicker tool?

I am working with 2 datepickers that have similar structures, but different names. The first one has the id "fecha_1_1" and the second one has the id "fecha_1_2". <div class="col-sm-3"> <p>Desde</p> <div class="f ...

How can I set a condition to open a specific page in ReactJs?

Currently, I am in the process of developing a website and have successfully implemented a profile page. This profile page consists of three buttons - Settings, Favourites, and Posts. To enhance user experience, I decided to structure it as a multi-step fo ...

Traverse numerous arrays in JavaScript

I am attempting to search through three separate arrays of strings using Javascript. The goal is to find a user-inputted name and determine in which array it is located. Here is an example of what I am trying to achieve: HTML let users = ['mario&a ...

An item was shown on the HTML page

Having some trouble displaying the graph generated by my R function on the opencpu server. Instead of the desired plot, all I see is [object Object] in the HTML page. Below is the snippet of code from my AngularJS controller: var req = ocpu.rpc("plotGraph ...

Ways to modify the default text in a dropdown menu?

I'm currently attempting to modify the title of a dropdown using the Multi-select plugin found here. However, I've encountered an issue where I am unable to dynamically change the text (Dropdown title) of the dropdown using JavaScript. $(' ...

c# JavaScriptConverter - understanding the deserialization of custom properties

I'm facing an issue where I have a JSON serialized class that I am trying to deserialize into an object. For example: public class ContentItemViewModel { public string CssClass { get; set; } public MyCustomClass PropertyB { get; set; } } Th ...

Issue with Angular 18 component not being displayed or identified

Recently, I began building an Angular 18 application and encountered an issue with adding my first component as a standalone. It appears that the app is not recognizing my component properly, as it does not display when added as an HTML tag in my app.compo ...

Enabling or disabling select input based on the selected option in a previous select dropdown

My goal here is to customize a select input with 3 options: Sale, Rent, Wanted. Based on the selection, I want to display one of three other select inputs. For example, if "Sale" is chosen, show the property sale input and hide the others. However, when su ...

Comparison Between Angular and Web API in Regards to Racing Condition with Databases

Currently, I am working on an Angular service that iterates through a list and makes web API calls to add or modify records in the database. The service operates on a small record set with a maximum of 10 records to update. After the loop completes, Angula ...

"The text() or json() methods in Javascript's fetch function never seem to resolve, leaving the operation in a perpetual

In my new nextjs 13 project, I'm attempting to perform a fetch operation (unsure if it's related to JavaScript or nextjs) and using console.logs to monitor the code execution. let url = `${BASE}/${module}/${path}`; url += "?" + ne ...

AngularJS - real-time validation using the $valid property

I have implemented AngularJS to handle form validation and submission. The submit button is configured as follows: <button type="submit" ng-disabled="btn" ng-click="submit(settings.$valid)" class="btn btn-primary"> Submit </button> The butt ...

Methods for passing JavaScript variables to PHP

I have encountered this problem on Stack Overflow before, but I couldn't find a solution that worked for me. I am using Codeigniter and have a form where users can rate a product. What I need to achieve is to insert the user's rating into the dat ...

The HTML select element fails to drop down over the THREE.js scene

I'm currently working on enhancing the Three.js editor for a project. editor link One of the tasks I'm tackling is adding a select element on top of the viewport in the editor. Unfortunately, the dropdown functionality of the select element isn ...

Activate inactive html button using javascript

One of the challenges I am facing is testing forms where the client specifically requested that the submit button be disabled by default. I have been exploring ways to dynamically replace the disabled="" attribute with enabled using JavaScript within a s ...