Tips for identifying the highest number of repeating "values" in a JavaScript array

My problem is similar to the question asked here: Extracting the most duplicate value from an array in JavaScript (with jQuery)

I tried the code provided, but it only returns one value, which is 200.

var arr = [100,100,200,200,200,300,300,300,400,400,400];
    var counts = {}, max = 0, res;
    for (var v in arr) {
      counts[arr[v]] = (counts[arr[v]] || 0) + 1;
      if (counts[arr[v]] > max) { 
        max = counts[arr[v]];
        res = arr[v];
      }

    }
    console.log(res + " occurs " + counts[res] + " times");

Please help me modify the code to return multiple values, not just one...

The expected result should be: 200, 300, 400. Please assist, thank you!

Answer №1

To determine the most frequently occurring result, you need to loop through your counts and find the maximum value.

var arr = [100,100,200,200,200,300,300,300,400,400,400];
    var counts = {}, max = 0, res;
    for (var v in arr) {
      counts[arr[v]] = (counts[arr[v]] || 0) + 1;
      if (counts[arr[v]] > max) { 
        max = counts[arr[v]];
        res = arr[v];
      }

    }
    var results = [];
    for (var k in counts){
      if (counts[k] == max){
        //console.log(k + " occurs " + counts[k] + " times");
        results.push(k);
      }
    }
    console.log(results);

Answer №2

Generate an Object by iterating through an array that contains the indices of the most frequently repeated values, as shown below

var arr = [100,100,200,200,200,300,300,300,400,400,400];
valObj = {}, max_length = 0, rep_arr = [];

arr.forEach(function(el,i){
   if(valObj.hasOwnProperty(el)){
       valObj[el] += 1;
       max_length = (valObj[el] > max_length) ? valObj[el] : max_length
   }
   else{
       valObj[el] = 1;
   }
});

Object.keys(valObj).forEach(function(val){
    (valObj[val] >= max_length) && (rep_arr.push(val))
});
console.log(rep_arr);

Once the object is created with keys as array values and values as array indexes of those values, you can manipulate or analyze it further. I hope this explanation is helpful.

Answer №3

It's not recommended to use for..in for iterating through an array. For more details, you can refer to this link.

Below is a helpful code snippet:

var arr = [100, 100, 200, 200, 200, 300, 300, 300, 400, 400, 400];
// Using reduce function to create an object where keys are 100, 200, 300
// and their values represent the number of times they have appeared
var m = arr.reduce(function(i, v) {
  if (i[v] === undefined) {
    i[v] = 1
  } else {
    i[v] = i[v] + 1;
  }
  return i;
}, {});
// Finding the maximum value from the object,
// getMaxRepeated will be 3 in this case

var getMaxRepeated = Math.max(...Object.values(m));
// An array to store elements that are repeated 'getMaxRepeated' times
var duplicateItems = [];

// Iterating through the object and adding keys that are repeated
// 'getMaxRepeated' times to the duplicateItems array
for (var keys in m) {
  if (m[keys] === getMaxRepeated) {
    duplicateItems.push(keys)
  }
}
console.log(duplicateItems)

Answer №4

A simple solution to count the occurrences of numbers in an array is by using the reduce method. Here's an example assuming all items in the array are numbers:

// Sample array of numbers
var arr = [300,400,200,100,100,200,200,200,300,300,300,400,400,400];

// Reduce the array to an object with number occurrences
var obj = arr.reduce(
  (o,key) => {
    o[key] = (o[key]) ? o[key]+1 : 1;
    return o;
  },
  {}
);

// Convert the object to an array of objects with keys and occurrences
var sorted = Object.keys(obj).map(
  key => ({ key: parseInt(key), occurs: obj[key] })
).sort(
  (a,b) => (b.occurs - a.occurs === 0) ? a.key - b.key : b.occurs - a.occurs
);

// Find and output the numbers with the highest occurrences
console.log(
  sorted.filter(
    item => item.occurs === sorted[0].occurs
  ).map(
    item => item.key
  )
);

Answer №5

Check out the code snippet below for a function that removes duplicate elements from an array:

function getDuplicate( arr ){
    let obj = {}, dup = [];
    for(let i = 0, l = arr.length; i < l; i++){
        let val = arr[i];
        if( obj[val] /**[hasOwnProperty]*/ ) {
            /**[is exists]*/
            if(dup.find(a => a == val) ) continue;
            /**[put Unique One]*/
            dup.push(val);
            continue;
        };
        /**[hold for further use]*/
        obj[val] = true;
    }
    return dup;
};

Test the function with the following array:

getDuplicate([100,100,200,200,200,300,300,300,400,400,400]);

Answer №6

Check out the code snippet below:

const numbers = [10, 10, 20, 20, 20, 30, 30, 30, 40, 40, 40];

let tempMap = {}

for (let i = 0; i <= (numbers.length - 1); i++) {

    let numToCheck = numbers[i];

    if (tempMap[numToCheck]) {
        tempMap[numToCheck] = tempMap[numToCheck] + 1;
    } else {
        tempMap[numToCheck] = 1;
    }
}

let maxCount;
Object.values(tempMap).forEach(value => {
    

    if (maxCount === undefined) maxCount = value;

    if (maxCount < value) maxCount = value;
});

console.log(maxCount);

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

Easily submit both FormData and a string in a single function call

I am trying to send data from a form (including a file input and string input) via ajax to an ASP.NET Function. When sending only files, I use the following code: function readURL() { var input = document.getElementById("fileUpload"); var files ...

The problem with React useState not updating could be due to useRef interference

I'm facing a strange issue with my React code: the useState function is not updating the view, despite trying everything to fix it. To illustrate the problem, I have created a simple example: function(){ const [enterJob, setEnterJob] = useSt ...

"When using `app.use(express.static`, it appears that the functionality is not working properly when the app is a sub

I attempted to implement something similar to this: var main = express(); main.use(express.static(path.resolve('./asset'))); main.route('someroute', someHandle); var app = express(); app.use(express.static(path.resolve('./asset&ap ...

JavaScript event triggered when an element is displayed on the page using AJAX

Is it feasible in JavaScript to initiate a function when an element, like a div, becomes visible on the screen? I am working on an infinite grid that expands in both directions, and I want to fetch elements dynamically through AJAX as the user scrolls. A ...

Fixing an erroneous value that has been dragged into the drop function with Jquery

I am encountering an issue with my codes and need some assistance in identifying the problem. The data is being dynamically loaded from the database, and I am using a foreach loop to display all items in a draggable div. The issue arises when I drag an it ...

I must convert this option into a checkbox

I am facing a challenge with this task, where I need to convert a select form into a checkbox form. Although I have managed to change the visuals, the functionality of the checkboxes does not match that of the select form. Below is the original select for ...

Tips for refreshing a GET request within a Vue.js application

I am receiving data from my Rails API backend and I would like to automatically refresh that GET request every 15 seconds. This way, if there are any changes on the backend (for example, if a POST request is made to another route), it will reload and retri ...

The submit button remains unresponsive, yet upon removing its JavaScript code, it functions smoothly

This is the content of my index.html file. It contains JavaScript code. However, there seems to be a problem with the JavaScript validation as the Submit button does not perform any action when clicked. Surprisingly, when I remove the JavaScript code, the ...

reasons why the console is not logging updated states

I'm having trouble logging the updated state values after using setState. The values seem to be updating fine in the render function, but not in the tokenAccess() method. Can anyone explain why this is happening? import React, { Component } from &apo ...

How can I go about refreshing my mapbox gl source data?

Hey there, I'm encountering an issue when attempting to update my mapbox source on click. I currently have two sources (cells, heatmap), and I am trying to add a new source using this code snippet: this.map.addSource("points", { type: "geojson", ...

Removing a row from a table seamlessly without the need to reload the page

I am having an issue with my page that displays a list of orders. When a user clicks on a button to delete a row from the table, it only removes the first row successfully. However, when attempting to delete the second or third row, it does not work. Can s ...

Tips for simulating an axios request that returns an image buffer

I am attempting to simulate an axios api call that returns an image buffer as shown below: <Buffer ff d8 ff e0 00 10 4a 46 49 46 00 01 01 00 00 01 00 01 00 00 ff e1 00 de 45 78 69 66 00 00 49 49 2a 00 08 00 00 00 06 00 12 01 03 00 01 00 00 00 01 00 ... ...

Having trouble extracting the date modified from a JSON file

I am able to retrieve section name, URL, web title, and headline from parsing JSON data with this code snippet. However, I seem to be encountering an issue where I cannot extract the last modified date. Here is the JSON structure: { "response":{ ...

Creating multiple objects in a threejs instance with varying sizes and positions

Recently, I decided to try out the InstancedBufferGeometry method in order to improve performance when rendering thousands of objects. Specifically, I wanted to create instances of cube geometries with varying heights. AFRAME.registerComponent('insta ...

Strange symbols keep appearing in my output from PHP

My current task involves generating a SQL query based on some inputs. I have a predefined SQL statement, in which I perform certain replacements, that will use these inputs to generate the required SQL through an ODBC connection. For now, I have stored th ...

Utilizing v-model alongside various JavaScript plugins within a single select element

I've incorporated the jQuery plugins select2 and datepicker into my project, utilizing custom directives for them. Everything was functioning smoothly until I attempted to retrieve the selected value using v-model, which resulted in a failure to bind ...

What is the process for generating an alert box with protractor?

While conducting tests, I am attempting to trigger an alert pop-up box when transitioning my environment from testing to production while running scripts in Protractor. Can someone assist me with this? ...

Switching the hierarchy of list items in React

I have a JSON structure with nested elements. const JSON_TREE = { name: "PARENT_3", id: "218", parent: { name: "PARENT_2", id: "217", parent: { name: "PARENT_1", i ...

Caught in the midst of a JSON update conundrum

I need some help with my JavaScript/JSON coding. I have a script that loads JSON data and displays it on an HTML page. Now, I want to know how I can update this data. Specifically, I want the script to update the location of the person when a button is cli ...

Protractor is displaying an error message of "unable to locate element testability" when attempting to access an element

I'm encountering an issue with Protractor while trying to access a variable that stores the return value of "elements.all". As someone who is new to Protractor, I wasn't sure how to select elements by a custom attribute. Thankfully, I received so ...