Determine the frequency of each element in the array

Given an arbitrary array, the goal is to determine the unique elements in the array along with their respective count. While I have managed to identify the unique elements within the array, I am struggling to establish a way to associate each element with its count. Any suggestions on how to achieve this without utilizing functions? I am new and haven't delved into functions yet.

var arr = [3, 4, 4, 3, 3];
var new_arr = [];
for (i = 0; i < arr.length; i++) {
if (new_arr.includes(arr[i])) {
// pass
} else {
new_arr.push(arr[i]);
}
}
console.log(new_arr);

Answer №1

Instead of using an Array, opt for an Object to maintain the count. Assign the number as the `key` and its count as the `value`.

Check out Array#reduce method for reference.

const res = [3, 4, 4, 3, 3].reduce((acc,cur)=>{
  
  if(acc[cur]) acc[cur]++;
  else acc[cur] = 1;
  return acc;

}, {});

console.log(res);

Alternatively, achieve the same without utilizing any methods:

var arr = [3, 4, 4, 3, 3];
var new_arr = {};
for (i = 0; i < arr.length; i++) {
  if (new_arr[arr[i]]) {
    new_arr[arr[i]]++;
  } else {
    new_arr[arr[i]] = 1;
  }
}
console.log(new_arr);

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 way to determine the size of an array following the use of innerHTML.split?

There is a string "Testing - My - Example" I need to separate it at the " - " delimiter. This code will help me achieve that: array = innerHTML.split(" - "); What is the best way to determine the size of the resulting array? ...

Encountering a CORS policy issue while trying to load a font in three.js TextGeometry

Recently, I've been delving into the world of three.js. In an attempt to display some text, I encountered a roadblock in the form of a CORS policy access blocked error related to loading a font file. Despite double-checking the path and experimenting ...

Making synchronous HTTPS requests in Node.js is a useful feature for

Here is the code snippet I am working on: `//... .then(function () { var opts = { method: 'GET', agent: new https.Agent({ rejectUnauthorized: false }) }; var url = 'https://***'; ret ...

Querying an array using the Contentful API

Recently, I've been experimenting with the Contentful API (content delivery npm module) and have encountered a challenge that I'm not sure how to overcome. In my Contentful setup, I have a content type called tag which consists of one field, als ...

Trouble converting string to array of strings and strings to array of integers

Trying to input 1 + 1 into an edit text by pressing app buttons, converting integers to strings to display them together as 11 instead of the sum (=2) is causing a "FATAL EXCEPTION" error with this line of code when any number button is pressed. Error "FA ...

Decipher intricate JSON with JavaScript

After retrieving a JSON object from Mongo DB, I have this data structure. **JSON** { "_id" : ObjectId("5265347d144bed4968a9629c"), "name" : "ttt", "features" : { "t" : { "visual_feature" : "t", "type_feature" : ...

Guide to sending an array to a Node.js web service using AngularJS

Attempting to add an array of data to a Node.js web service using the code below. $scope.addList = function(task,subtask){ subtask.checked= !(subtask.checked); var data = { "taskId": task._id, "subTaskName": subtask.subTaskNa ...

When using the POST method with npm http-server, an error 405 is thrown

I'm attempting to send an Ajax request to execute a php file on a local http server. However, the browser console shows Error 405: method not allowed. Even after trying solutions from similar questions and enabling CORS on the http-server, I still ca ...

Tips for sending an array of vectors in a function

I am facing a challenge with passing an array of vectors to a function in my code. Below is my code snippet: void gridlist(std::vector<int> *grid, int rows, int cols){ ..... } int rows=4; int cols=5; std::vector<int> grid[rows][cols]; g ...

Unable to utilize the instance once it has been created. An error is encountered stating "User.find is not a function" when attempting to retrieve documents

Currently, I am utilizing nodejs in conjunction with the expressjs framework and MongoDB. Within mongoose, an instance has been created using var User = new userModel(data). Below is my model located in user.js: const userModel = mongoose.model("User", ...

Using jQuery to determine the value and dynamically stay on the current page

Is there a way to ensure that the page stays the same if the login (data.login != 1) is incorrect? I attempted using preventDefault, but it doesn't seem to be effective. Can someone offer assistance? $(document).on('submit', '#login&ap ...

Encountering an issue when using both the Google Maps API and Google URL Shortener API within the same program

Recently, I developed a program that involves passing data to an iframe through a URL. However, due to the limitation of Internet Explorer supporting only 2083 characters in a URL, I decided to use the Google URL Shorten API to shorten the URL before sendi ...

Implementing a Standardized Template for Consistent Design and styling Throughout Website

As I work on building my website, I find myself struggling with some of the intricacies. The homepage is set up with a navbar and header, along with several pages that can be easily navigated to. While everything seems to be functioning properly, upon ins ...

Horizontal scroll functionality featured in a D3 bar graph

I'm currently working on implementing a bar graph with a selection dropdown that includes 3 values: By Date, By Week, By Month (where 'By Date' is the default option). When retrieving data from the backend for 'ByDate', I have a l ...

Importing values from one array to a new array

I am dealing with an Object[] containing types that I need to extract into a Class[]<?>. Once this is done, I will be passing them to the following method: public static void invokeMethod(String className, String methodName, Class<?>[] ...

Analyzing JSON data sets and computing the mean value

I need help extracting specific data from the JSON dataset provided below. This is my first time working on such tasks, so any assistance is greatly appreciated. [ { "id": 1, "model": "Madza 2", & ...

Node.js Promise function halting execution prior to returning

How can we adjust the code provided below to allow the getUser(theToken) promise function to successfully return its internally generated valid value without freezing? app.get('/auth/provider/callback', function(req, res) { var queryData = u ...

Unable to successfully send a POST request from the client-side frontend to the local node server; only GET requests are functioning properly

While attempting to submit a post request to my local server at localhost:8080/page, I encountered the message 'Cannot GET /page'. My browser is Google Chrome and the network tab in the developer tools shows: Below is the front end code featurin ...

Tips for properly utilizing the setState method to update an object property within an array in a class component

In my current project, I have an array of objects stored in the state. Here is an example of the structure: const arrayOfTests = [ { id: 1, name: "test1", description: "test description"    }, {     ...

JavaScript: The function is encountering issues with properly formatting the numbers

I am currently facing an issue with a function I have created to format numbers for currency by inserting commas every 4 digits. The problem lies in the fact that the first 4 numbers do not have a comma added where it should be, and the formatting only wor ...