Analyze the elements within arrays and determine the occurrence rate of each element

Issue at hand:

var rawData = [[two],[three],[four],[one],[two],[two],[two],[three],[four],[five],[three],[four],[five]];

Given an array of arrays, the goal is to identify the unique elements within one of the arrays and provide a count of each unique element, presenting the results in two separate arrays as follows:

var uniqueList = [one,two,three,four,five...]
var count = [countOfOne, countOfTwo, countOfThree, countOfFour, countOfFive...]

(It should be noted that rawData is subject to change as data is sourced from a large spreadsheet.) What would be the most effective method to accomplish this task?

Answer №1

Maybe it can be done this way? Both instances could also utilize reduce, but I personally find it more challenging to decipher.

let list = {}
const rawData = ["two","three","four","one","two","two","two","three","four","five","three","four","five"]
  .forEach(item => {
    const obj = list[item] || { count: 0 };
    obj.count = obj.count ? obj.count + 1 : 1;
    list[item] = obj;
  });


 ["one","two","three","four","five"].forEach(item => console.log(item,list[item]))

Only including elements from the comparison array

let list = {}
const compareList  = ["two","three"];
const rawData = ["two","three","four","one","two","two","two","three","four","five","three","four","five"]
  .forEach(item => {
    if (compareList.indexOf(item) !=-1) {
      const obj = list[item] || { count: 0 };
      obj.count = obj.count ? obj.count + 1 : 1;
      list[item] = obj;
    }
  });


 console.log(list)

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

JS Executing functions in a pop-up window

Recently, I have been immersing myself in learning JS and experimenting with webpage interactions. It started with scraping data, but now I am also venturing into performing actions on specific webpages. For example, there is a webpage that features a butt ...

Exploring the possibilities of node-webkit: node-odbc encounters a setback

Currently, I'm in the process of developing a desktop application utilizing node-webkit. The main functionality of the app involves querying an Oracle database. To establish the connection with the database, I have integrated node-odbc. To ensure tha ...

Retrieve individual item

It has been a few days since I started working on this. I am attempting to create a query that retrieves all businesses registered in a specific city. Subsequently, for each business, I aim to fetch all products associated with that business and then cons ...

Reloading nested Iframe with Selenium automation script

Currently, I am facing a challenge while working on an application that contains nested Iframes within the user interface. Some of these Iframes undergo refreshing during the test execution process. Is there any approach that allows us to simulate the refr ...

Issue with AWS SDK client-S3 upload: Chrome freezes after reaching 8 GB upload limit

Whenever I try to upload a 17 GB file from my browser, Chrome crashes after reaching 8 GB due to memory exhaustion. import { PutObjectCommandInput, S3Client } from '@aws-sdk/client-s3'; import { Progress, Upload } from "@aws-sdk/lib-storage& ...

Invoke the parent method within the child application

I have a checkbox on the child app controller. When the user clicks it, I need to call a method from the parent controller: Parent app controller: <div ng-controller="ParentCntr as parentCntr"> <child-app></child-app> </div> C ...

Encountering a TypeError: relativeURL.replace is not a valid function in Next.js

Why am I encountering this error in my Next.js application? TypeError: relativeURL.replace is not a function. (In 'relativeURL.replace(/^/+/, '')', 'relativeURL.replace' is undefined) Request.js file const API_KEY = process ...

Retrieve the numerical suffix from a key that begins with a particular substring

Within my array, there exists an array key in the form of show_me_160. This key may vary slightly, for example, it could be show_me_120 on a different occasion. I am interested in knowing whether it is feasible to compare the array key up to the final _ ...

Does this function only function on a singular div?

I need some help! I'm having trouble getting a function to trigger on the divs below the initial one. Any advice? ...

Transmit information to the client-side webpage using Node.js

One of the main reasons I am diving into learning Node.js is because I am intrigued by the concept of having the server send data to the client without the need for constant querying from the client side. While it seems achievable with IM web services, my ...

Maintain checkbox state through page reloads using ajax

Currently, I am troubleshooting a script that is intended to keep checkbox values checked even after the page is reloaded or refreshed. The code snippet below was implemented for this purpose, but unfortunately, it doesn't seem to be functioning corre ...

Carry out numerous commitments across a range of elements

I have a list of objectIds and I want to perform operations on different collections based on each Id. I prefer executing the operations sequentially. var removeOperation = function(objectified){ return Comps.findOne({reviews : objectified}).populate([ ...

Converting a Javascript object to JSON format only once using AngularJS

Is it possible to convert a JavaScript object to JSON using angular.toJson only once in my code? Here is an example: $scope.task.tags = [{"id":22,"tag":"printer","created_at":"2016-03-15" }]; $scope.create = function(task) { tmp.tags = angular.toJson( ...

The $scope.$watch function does not activate with each individual change

Yesterday, I realized that in my angularJS 1.4.8 application, the $scope.$watch doesn't trigger on every change causing a bug to occur. Is there a way to make it work on every change immediately? For example, in this code snippet, I want the function ...

Bug allows unauthorized access to password in Bootstrap Password Revealer

Whenever I try to reveal a Bootstrap password using the eye button, my PC freezes. Strangely, an input is automatically added even though there are no codes for it. This auto-increasing input causes my browser to hang and eventually crashes my entire PC. C ...

Refresh Material-Ui's Selection Options

Is there a way to properly re-render the <option> </option> inside a Material UI select component? My goal is to transfer data from one object array to another using the Material UI select feature. {transferData.map(data => ( <option ...

Node.js Express not inserting data with Mongoose when using form data

For the past two weeks, I have been struggling to post data to insert into a database using form-data. It consistently shows a 400 bad request error. Below is my code for server.js: require('./db.js') let express = require('express') ...

Utilize CSS to format the output of a script embedded within

When I embed the following script in my HTML, the output doesn't have any styling. How can I style the script output to blend well with the existing HTML structure? I tried accessing the output by ID, but couldn't figure it out. <script> ...

Using AJAX to submit a form to a CodeIgniter 3 controller

I am working on adding a notification feature and need to run an ajax query through the controller when a button is clicked. Here's the script I'm using: $('#noti_Button').click(function (e) { e.preventDefault(); ...

How can I retrieve a formController in AngularJS?

When trying to reset the data in a form and calling form.setPristine(), I encounter an issue where the formController is not registered within the $scope. It may sound like a basic question, but how can I locate the formController? Within the code snippe ...