Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

209
Views
Finding the mode of each column in a two-dimensional array - JavaScript

Not a question, just putting this out there if someone would need it. (caused me a lot of headache)

The script below can take a 2d array of any number number of 2nd-layer arrays as 'myArray' and create a single array of the most frequent element (regardless of type) in each column of the original 2d array.

myArray = myArray[0]
  .map((_, col) => myArray.map((row) => row[col]))
  .map((array) =>
    array.reduce(
      (a, b, i, arr) =>
        arr.filter((v) => v === a).length >= arr.filter((v) => v === b).length
          ? a
          : b,
      null
    )
  );
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

What it does: The code below will take any two-dimensional array “myArray” and return a one-dimensional array with the mode of each column of the original 2-d array.

How it works: The input (2-d array) is transposed and the resulting array is searched for the most common element in each row. It is then reduced to then flattened (reduced) and re-transposed to a 1d array containing the most common elements of each column of the original array.

myArray = [
  [1, 2, 3, 4, 5],
  [1, 2, 3, 4, 7],
  [1, 3, 3, 6, 7],
  [1, 5, 3, 4, 7],
  [1, 6, 3, 4, 7],
  [1, 7, 3, 8, 5],
];

myArray = myArray[0]
  .map((_, col) => myArray.map((row) => row[col]))
  .map((array) =>
    array.reduce(
      (a, b, i, arr) =>
      arr.filter((v) => v === a).length >= arr.filter((v) => v === b).length ?
      a :
      b,
      null
    )
  );

console.log(myArray);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!