Look for duplicate values in an array, retrieve the value, and determine the frequency

I've populated an array with a random number of strings.

var array = ["car", "plane", "plane", "car", "car"];

I want to access the values in the Array and count how many times each one has been added. For example:

var a = "car";
var aCount = 3;
var b = "plane";
var bCount = 2;

var text = "'" + a + "'" + " was found " + aCount + " times";
return text

I'm not sure how to use a loop to compare array[i] with all other values in the array, especially since the length of the array is random?

Thank you.

Answer №1

Transform the array values into keys and start tallying!

let valueCount = {};
for (let index = 0; index < values.length; index++) {
    if (valueCount.hasOwnProperty(values[index])) {
        valueCount[values[index]]++;
    } else {
        valueCount[values[index]] = 1;
    }
}

The object valueCount now stores the count of each array value.

Example: http://jsfiddle.net/oe0x6dbg/

Answer №2

To achieve this, you can utilize the Array.reduce method:

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

var result = items.reduce(function(counts, item) {
                 counts[item] = (counts[item] || 0) + 1;
                 return counts;
             }, {});

for(var key in result) {
    console.log('\'' + key + '\' appeared ' + result[key] + ' times');
}

/*
    Result:
    --------
    { 'apple': 3, 'banana': 2 }

    Console Output:
    ----------------
    'apple' appeared 3 times
    'banana' appeared 2 times
*/

Answer №3

You have the power to make it happen

let myArray = someArray.join();
let finalResult = {};

for (let index = 0; index < someArray.length; index++) {
    finalResult[someArray[index]] = myArray.match(new RegExp(someArray[index], "g")).length;
    myArray.replace(new RegExp(someArray[index], "g"), "");
}

console.log(finalResult); // {bike: 2, skateboard: 1}

Answer №4

An easy fix might involve introducing a "counter" variable as shown below:

var array = ["dog", "cat", "cat", "dog", "dog"];

var counter = {};

// Assign each element in the array to a key in the object
for (var i = 0; i < array.length; i++) {
    if (typeof counter[array[i]] === 'undefined') {
        counter[array[i]] = 1;
    } else {
        counter[array[i]]++;
    }
}

// Iterate through the object and display the counts
for (var item in counter) {
    console.log("'" + item + "'" + " appeared " + counter[item] + " times");
}

JSFiddle Link

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 is the process for implementing THREE.EdgesGeometry on a model imported using THREE.OBJLoader?

I have been attempting multiple times to add edges in a model loader using the OBJLoader, but I am unable to achieve it. Mloader = new THREE.MTLLoader(); Mloader.setPath( dir ); Mloader.load( mtl_dir, function ( materials ) { ...

Tips for resizing a Numpy array using zero padding

I am facing a challenge with reshaping a Numpy array. The current array looks like: array([1, 2, 3, 4, 5, 6, 7, 8]) My goal is to reshape it into an array that resembles: array([[5, 0, 0, 6], [0, 1, 2, 0], [0, 3, 4, 0], [7, 0, 0, 8] ...

Troubleshooting Django Templateview: Incorporating Bootstrap Popovers into HTML tables not functioning properly

https://i.stack.imgur.com/LXHJF.pngWhen loading this template, the HTML renders correctly and the table loads successfully. However, certain cells have special pop-over attributes that do not work after the HTML is loaded via an AJAX request on the same pa ...

An error occurred when attempting to set state within a nested fetch

Having difficulty solving an issue with react.js. loadFromServer(pageSize) { fetch('http://localhost:8080/api/employees') .then(response => { return fetch('http://localhost:8080/api/profile/employees', ...

Error in Passport JS: Trying to use an undefined function

I've been struggling with debugging my code in Express and Passport. I've tried following solutions from others but can't seem to get it right. Any help or useful links would be greatly appreciated. Here is the error message along with the ...

Using React's useEffect to implement a mousedown event listener

I created a modal that automatically closes when the user clicks outside of it. method one - involves passing isModalOpened to update the state only if the modal is currently open. const [isModalOpened, toggleModal] = useState(false); const ref = useRef(n ...

What could be causing the list index to exceed its range in this particular scenario?

N = 3 sum1 = 4 rows, cols = (N+1, sum1+1) dp = [[-1 for i in range(rows)] for j in range(cols)] for i in range(0, cols): dp[0][i] = False for i in range(0, rows): dp[i][0] = True I'm struggling to understand why I keep encountering a lis ...

Steps for building a Bootstrap grid of thumbnails

I need to display an unknown number of thumbs. Below is a sample of the HTML rendered: <div class="row-fluid"> <ul class="thumbnails"> <li class="span3"> <a href="#" class="thumbnail"> &l ...

The use of url.resolve() function with greater than two arguments

Currently, I'm utilizing the url.resolve() function to combine components of a URL from a configuration file in this manner: var uri = url.resolve(config.baseUrl, this.orgId, this.appId, type) However, it appears that using more than two arguments d ...

In ReactJS, when passing an array of objects to a child component, the first instance may sometimes return as undefined, causing the code to break

Currently, I am in the process of creating a personal blog for my brand. The "Posts" section is designed to retrieve data from a basic JSON via an API. At present, I have used mirageJS to mock the API and employed the useEffect and useState hooks to set th ...

Experiencing a Typescript issue while trying to set a string as the state of a React component with a specified TS type

I've defined a state in my React component for a specific data type called Color. \\ state const [messageSeverity, setMessageSeverity] = useState<Color>('success'); \\ TS type export type Color = 'success&ap ...

Attempting to display a webpage in node.js following a successful post request via AngularJS

I am facing an issue with rendering a page from Node.js after a post request from the Angular controller. Despite no errors in the console, the page does not load and remains on the same page. I can see that the page is loaded under the Network--Preview Se ...

What is the best way to enable editing of a form when the edit button is clicked?

I have created a simple profile page where users can edit their profile information. I have placed a button at the end of the page. Initially, the form should be uneditable, but when the button is clicked, the form becomes editable. I attempted to use `dis ...

Creating a concurrent_vector based on the guidelines outlined in Intel's blog

I am currently working on developing a thread-safe lockless container that is similar to std::vector, based on the principles outlined in this insightful article here. My understanding is that, instead of using a single contiguous array like std::vector, ...

Delete a designated section from a URL with the power of jQuery

I have a URL like http://myurleg.com/ar/Message.html and I need to change ar to en in it when clicked on. For example, if my current URL is: http://myurleg.com/ar/Message.html After clicking, it should become: http://myurleg.com/en/Message.html I attemp ...

Using Angular Directive to create a customized TreeView

Although I am still relatively new to Angular, I need to make some modifications to a treeview directive that I found on NgModules. The existing code looks promising, but I want to customize it to include the ability to add, delete, or modify items. You c ...

Defining an array with all dimensions except the highest one specified

What size will the integer array arr be if it is declared in the following way: int arr[][2]={1,2,3}; What is the reason for not specifying the highest dimension? ...

How can I use jQuery to either display or hide the "#" value in a URL?

I have a question that I need help with. Let's say I have the following links: <a href="#test1"> Test </a> <a href="#test2"> Test 2 </a> When I click on Test, the URL will change to something like siteurl/#test1. However, whe ...

How can I make sure that my function returns a mutated object that is an instance of the same class in

export const FilterUndefined = <T extends object>(obj: T): T => { return Object.entries(obj).reduce((acc, [key, value]) => { return value ? { ...acc, [key]: value } : acc; }, {}) as T; }; During a database migration process, I encounte ...

Adding a prefix to all specified routes in Express.js

Imagine having an Express app defined in a file called server.js as follows: const app = express(); app.use('/foo', foo); app.use('/bar', bar); module.exports = app; You then import this Express app into another file named index.js: ...