Determining the Most Frequent Number in an Array Using Reduce and Filter in JavaScript

Looking at this function:

const mode = arr =>
  arr.reduce(
    (a,b,i,arr) => (arr.filter(c=> c === a).length >= arr.filter(c => c === b).length) ? a : b,  
    null
  )

console.log(mode([500, 450, 400, 400, 375, 350, 325, 300])) // 400

It appears that the reduce function is being used with a custom function as the first argument and null as the second. The custom function inside looks like it's creating a ternary conditional comparing elements of the array.

I'm still unsure about the inner workings of this code and would appreciate a simple breakdown to understand it better. Currently, it seems to work for finding the mode if there is only one in the array, which is fine for now, but I may need to address that later.

Here is a link to a CodePen where you can test it out.

Answer №1

This specific function is designed to process two elements at a time from an array, applying a designated function to them. It then continues this process by combining the result with the next element, and so on for all elements within the arr.

The core functionality of the function involves comparing the occurrences of 'a' and 'b' within the array and returning the value that appears most frequently between the two.

To determine the number of occurrences, it utilizes the method filter(c => c === a), which essentially filters out elements equal to a into a new array.

By following this filtering logic, the end goal is to identify the element that has the highest frequency in the array.

For the provided example scenario:

  1. #of 500s vs #of 450s ==> results in 500 (due to >=)
  2. #of 500s vs #of 400s ==> results in 400 (as 400 appears twice)
  3. #of 400s vs #of 400s ==> results in 400
  4. #of 400s vs #of 375s ==> results in 400
  5. #of 400s vs #of 350s ==> results in 400
  6. #of 400s vs #of 325s ==> results in 400
  7. #of 400s vs #of 300s ==> results in 400

The final outcome is determined based on the last comparison made.

Answer №2

When the arr.filter function is called, it takes a value and returns an array containing only that number. In the original array, this will result in an array with a single item for each element, except for 400 which appears twice.

If the length of the array with the accumulator value is greater than the array with the current value, the accumulator is returned. The initial accumulator value is null, so when comparing [] and [500], 500 becomes the accumulator.

The comparison continues with [500] and [450], with the accumulator remaining at 500. When 400 is added to the mix, the comparison is between [500] and [400, 400]. The current value wins, making the accumulator 400. Since there are no other values in the array appearing more than twice, the reduce function ultimately returns 400.

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

Vue-powered carousel having trouble rotating properly

I recently came across a carousel created using vanilla javascript and html. I attempted to convert it to Vue, but encountered some challenges. The carousel is supposed to dynamically pull images from a SharePoint list. However, in my version, the images a ...

Using AngularJS and ServiceStack webservice, perform the "get('url')" operation

I'm completely new to AngularJS and I'm attempting to retrieve some JSON items from a webservice I quickly set up using ServiceStack. When I enter the URL in the browser, I can see the JSON object without any issues. However, for some reason Angu ...

Retrieve the Axios response without interruption, even in the event of an exception, when making API calls with multiple files

Currently, as a beginner diving into Vue.js, I am exploring the world of frontend development by integrating Vue with my Laravel backend. To streamline my API calls and make them more organized for different models, I decided to create a separate file name ...

How to Use JQuery Load to Load Google Maps?

Is it possible to ensure that the initialize() function is executed in the correct sequence of events so that a Google Map v3 API map can be loaded via a JQuery .load() method? The current code structure I've implemented is as follows: $('#mapl ...

Prevent index.html from being cached in the service worker in create-react-app

I am encountering an issue with my reactJs app that utilizes create-react-app. Despite updating the website or deploying a new build, Google Chrome always retrieves index.html from the service worker without making a network call. I suspect that caching o ...

Unable to remotely access the 'three.js' library

After including a path to the online three.js library in my <script> tag within the index.html file, I am facing an issue where there is no access to the three.js library resulting in my script not working properly. <script src="https://three ...

Tips for validating updates in MongooseEnsuring data integrity is

My current Schema does not validate upon updating. Can you please point out where I went wrong and help me fix it? ...

Place the child's text within the matching parent data element

I'm having trouble assigning the text values of children to their respective parent's data element, as all the values are being combined. Here is my code: HTML <ul> <li class="item" data-v="1"> <div class="xyz" data-v="2"> ...

Comparing HTML5 Drag and Drop to jQuery UI Drag and Drop: What's the Difference

In the ever-evolving world of web development, what is the most effective method for creating a drag and drop builder in 2017? While this question has been posed in the past (as seen here), technology changes rapidly. Is HTML5 still the go-to option, or ha ...

What steps can be taken to extend the duration that the HTML necessary validation message is displayed?

Is it possible to extend the duration in which the HTML required validation message is displayed? Currently, it seems to appear for too short a time. https://i.sstatic.net/DdqH6.jpg ...

Navigating and altering multi-dimensional arrays in the C/C++ programming languages

I'm stuck with arrays and pointers, even though I have an idea of what's wrong, I can't seem to find a simple fix. Here is the code snippet in question: void faceRotateACW(char *face[CUBE_DIM][CUBE_DIM]){ char tempFace[CUBE_DIM][CUBE_D ...

Guide to effortlessly loading files with designated decorators in a node.js application

Within the realm of Project A, I have constructed a decorator and am seeking a method to automatically load all these decorators upon initializing the application in Project B, which is the project utilizing Project A. Is there a way to accomplish this tas ...

Istanbul provides me with a thorough analysis, yet it always seems to conclude with an error

Currently, I am experimenting with a basic application (found in the Mocha tutorial code available at ) to troubleshoot why Istanbul is giving me trouble. The issue is that Istanbul successfully generates a coverage summary but then throws an error for unk ...

Add a text to the values in a column of a table when the IDs are the same

I am working on a project that involves updating a table based on a data change. The table has a column for ID and when the ID matches a specific variable, I need to append the word 'Updated!' next to it in the table cell. However, the code I hav ...

What is the best way to send a JSON object to bootstrap-table?

In my controller, I am passing a JSON encoded object to the view. Using a Bootstrap table in the view to display the data, but it is showing "No matching records found." Can someone please assist with this issue? Here is my controller: see image And here ...

Invoke `setState` function in contexts outside of React framework

Is the following approach guaranteed to work correctly within React v18 semantics? The "rules of hooks" only address calling the hook within the component, with no mention of whether it's acceptable to call the dispatcher returned from the ...

What is the best way to implement restful instead of query syntax in a $resource factory?

Recently, I set up a $resource factory like this: (function() { 'use strict'; app.factory('WidgetFactory', [ '$resource', function($resource) { return $resource('http://localhost:8282/widget/:widgetId&apo ...

Images copied using Gulp are often distorted or incomplete

There is a simple task of moving an image from one folder to another. gulp.task('default', function () { return gulp.src('./img/*.*') .pipe(gulp.dest('./image')); }); Previously, everything was running smoothly, b ...

Angular Starter Kit

When starting with Angular.js, there are various boilerplate kits available such as angular-seed, some incorporating requirejs and more. However, many of the options I've come across seem to be outdated. As a newcomer to Angular, I'm wondering if ...

What is the best way to run a series of basic commands in Node.js in sequence

Is there a way to execute 4 bash commands sequentially in nodejs? set +o history sed -i 's/&& !this.peekStartsWith('\/\/')/ /g' dist/vendor.bundle.js sed -i 's/&& !this.peekStartsWith('\/\/ ...