Achieving maximum occurrence with a 2D array using JavaScript

I'm trying to find the most commonly occurring string in a 2D array.

For example, given:

const arr = [['foo','bar','21'],
             ['foo', 'lar','28'],
             ['loo', 'bar','28']]

We can see that foo appears most frequently in column 1, bar in column 2, and 28 in column 3.

The size of the array may vary, so the solution needs to be dynamic.

I attempted a solution but it's complex and not suitable for multidimensional arrays:

function foo_func(array){
  if(array.length == 0)
    return null;
    var modeMap = {};
    var maxEl = array[0], maxCount = 1;
    for(var i = 0; i < array.length; i++){
      var el = array[i];
      if(modeMap[el] == null)
         modeMap[el] = 1;
   }
return maxEl;
}

If anyone has a cleaner or functional solution, I'd greatly appreciate it!

Answer №1

To transform data into an array structure, each containing objects with keys representing properties (e.g. 'foo') and values indicating the frequency of each property in the dataset:

const arr = [
  ['foo', 'bar', '21'],
  ['foo', 'lar', '28'],
  ['loo', 'bar', '28']
];

const columns = arr.reduce((a, subarr) => {
  subarr.forEach((item, i) => {
    if (!a[i]) a[i] = {};
    a[i][item] = (a[i][item] || 0) + 1;
  });
  return a;
}, {});

const highestInEachColumnEntries = Object.values(columns).map(
  obj => Object.entries(obj)
    .reduce(
      (a, b) => a[1] > b[1] ? a : b
    )
);

const highestInEachColumnKeysOnly = highestInEachColumnEntries.map(([key]) => key);
console.log(highestInEachColumnKeysOnly);

Answer №2

In one approach, start by rotating the array first.

After that, you can easily identify the most common elements using reduce and filter methods.

Finally, apply the common function to the rotated array using the map method.

const arr = [
  ['foo', 'bar', '21'],
  ['foo', 'lar', '28'],
  ['loo', 'bar', '28']
];

const rotated = arr[0].map((col, i) => arr.map(row => row[i]));
const common = arr => arr.reduce((a, b, i, arr) =>
     (arr.filter(v => v === a).length >= arr.filter(v => v === b).length ? a : b));
const result = rotated.map(m => common(m));
    
console.log(result);

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

The array is not preserved by Mongoose once the .map(...) loop has ended

I'm encountering an issue where every time the Node.js quits the loop of .map(...), my Post.attachments array reverts back to the state of []. I'm curious as to why this behavior occurs. Below is the code snippet: req.files.map(async (file) => ...

Unable to locate the module model in sequelize

Having some trouble setting up a basic connection between Postgres and SQL using Sequelize. I keep getting an error where I can't require the model folder, even though in this tutorial he manages to require the model folder and add it to the sync, lik ...

What is preventing me from being able to reach the instance of Cropper JS?

I'm facing some issues with executing the loadImage() function as I am unable to access the variable cropper. My ultimate objective is to run cropper.getCroppedCanvas and save its output value into an input field so that I can transmit it via AJAX. T ...

I have an array in JavaScript containing data objects within curly braces, and I want to disregard it

In trying to sum all values for each key in an array and create a new array with the key-total pairs, encountering difficulties when dealing with empty data represented by {}. To address this issue, attempting to validate that the data is not equal to {} b ...

assign a variable to the UISlider value

After spending a solid 12 hours attempting to crack this puzzle, I am still stumped! Admittedly, I am only about 3 weeks into my foray into Swift coding, with minimal prior experience (unless you count that rainbow I made on my Atari 800XL!). Confession: ...

Receiving an associative array as a result of a prepared statement

I've been struggling to retrieve an associative array from an SQL query using prepared statements. Everything I try doesn't seem to work, even though it was working fine before I switched to prepared statements. I'm getting conflicting infor ...

1. "Ensuring the URL of a New Tab Using WDIO"2

During my testing scenario: Navigate to link1 Click a button Open a new tab with link2 How should I verify the link2? I attempted using assert(browser).toHaveUrlContaining(''), but it only verified the link1, causing my test to fail. ...

Updating the color of HTML button text dynamically using JavaScript function

I am attempting to create a function that will change the text color of a button in a sequence - red on the first click, green on the second click, and back to black on the third click (and so forth). I thought this would be straightforward to achieve with ...

Having trouble clicking on an element in Selenium Webdriver with Python? It seems like the property 'click' is returning null

Encountering an error when attempting to execute this command: driver.find_element_by_link_text("Confirm").click() selenium.common.exceptions.WebDriverException: Message: unknown error: Element <a href="javascript:void(0);" class="c-button u-fontSize1 ...

Anticipated semicolon in the JavaScript file

I recently came across the dialogflow demo as a reference. However, I encountered an error stating 'semicolon expected' at the method sendTextMessageToDialogFlow. How can I resolve this issue? Below is the code snippet: router.post('/dialo ...

How does the Paginate Pipe effectively retrieve the array length in an Angular 2 application?

I find myself in an interesting situation where I have a piece of code that is functioning within my Angular 2 application - it's generating the correct value, but the method behind its success is unclear to me. Specifically, I am using ng2-paginatio ...

Setting up jQuery UI

I recently downloaded jQuery UI and found myself overwhelmed with the numerous files that came with it. I am unsure if I need to use all of them or where they should be placed. Here is what I have: css/ development-bundle/ js/ index.html I moved the fol ...

An error occurred in the main thread: java.lang.NegativeArraySizeException

This Java project is my biggest undertaking so far. I've been grappling with this error for hours on end. I suspect it's due to a mistake in my string handling. I'm aware that my code may not be very clear, and I'm eager to learn from m ...

Creating PDF files from an Angular-UI interface

What is the method for creating a PDF using Angular? We have utilized high charts to generate dynamic graphs and now I need to convert that data into a PDF. Could you please explain the approach for achieving this? <!DOCTYPE html> <html> & ...

NodeJS: Implementing external URL redirection functionality

I've set up a GET /auth route that is supposed to redirect to an external resource, like https://google.com. However, instead of redirecting me to the correct URL, it redirects me to http:localhost:3000/api/auth/https://google.com. Is there a way to ...

Utilize an index to retrieve the data stored within a div that consists of numerous rows (divs)

I have a main container with several rows nested inside, here is an example: <div id="containerDiv1"> <div class="paramRow"> <input type="text" value="Foo" id="param1" /> </div> <div class="paramRow"> ...

Halt the jQueryUI Slider once a specific difference or margin has been reached

I have a specific margin or distance that needs to be changed from an HTML select option tag dynamically in the future. I have implemented a Range Slider using jQueryUI Slider. My objective: I am looking to halt the sliding action once a specific distance ...

Error occurs when page rendering is stuck in a recursive loop: Excessive re-renders detected

My webpage contains several form components as listed below. While everything on the front end seems to be working fine, I noticed that the Fetchmovies function is being called repeatedly and an error is thrown in the console: caught Error: Too many re-ren ...

Selenium is not functioning correctly when used for web scraping with Python and Javascript

Currently, I am attempting to extract data from a flight-searching website that appears to be generated using Javascript. Despite several failed attempts with different methods, I have now turned to selenium as my next strategy. from selenium import webdr ...

During the initial render in next-auth, the useSuspenseQuery function is triggered to fetch data without a defined token, resulting in an

Recently, I've started implementing the new useSuspenseQuery feature from react-query and I couldn't help but notice that the enabled property is missing on this hook. This has caused an issue with my useGetApiToken function, as it initially retu ...