How can you identify the second least common integer in an array of numbers?

Seeking help with a JavaScript coding challenge that I'm stuck on, here is the question:

Create a function that takes an array of integers and returns an element from that array.

The function should calculate the frequency of each element (how many times it appears in the array) and ideally return the element with the second-lowest frequency. If that's not possible, it should return the element with the lowest frequency.

If there are multiple elements that meet the criteria, the second smallest one (based on value) should be returned.

Examples:

secondLowest( [4, 3, 1, 1, 2] ) === 1

secondLowest( [4, 3, 1, 1, 2, 2] ) === 2

secondLowest( [4, 3, 1, 2] ) === 2

Here is what I have so far, but I'm unsure how to proceed:


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

Answer №1

I made it a point to provide a flexible, parameterized function that doesn't rely on hardcoded numbers.

Your instance included two fixed values:

  • The second least frequency should be chosen
  • In cases of ties, the second least value should be chosen

Here's how the code operates:

  • Determine the frequency of each input value
  • Group together values with the same frequency
  • Sort these grouped pairs by frequency and select the nth-lowest (in this case, n=2)
  • If there are multiple pairs with the nth-lowest frequency, sort them by value, and choose the mth-lowest pair (in your example, m=2)
  • Return the value of this final pair

The m and n parameters mentioned here are denoted as freqInd and valInd in the code. Keep in mind that to choose the second-lowest frequency, freqInd should be 1, not 2 (as 0 would select the lowest, hence 1 picks the second-lowest).

let lowestFreqVal = (freqInd, valInd, values) => {
  
  // Compute frequencies in a map
  let f = new Map();
  for (let v of values) f.set(v, (f.get(v) || 0) + 1);
  
  // Group together all val/freq pairs with the same frequency
  let ff = new Map();
  for (let [ val, freq ] of f) ff.set(freq, (ff.get(freq) || []).concat([ val ]));
  
  // Sort these groups by frequency
  let byFreq = [ ...ff ].sort(([ freq1 ], [ freq2 ]) => freq1 - freq2);  
  
  // Here are all the items of the `freqInd`-th lowest frequency, sorted by value
  // Note that `[1]` returns an array of integers at the frequency, whereas `[0]` would return the frequency itself
  let lowestItems = byFreq[ Math.min(byFreq.length - 1, freqInd) ][1]
    .sort((v1, v2) => v1 - v2);
  
  // Return the `valInd`-th lowest value
  return lowestItems[ Math.min(lowestItems.length - 1, valInd) ];
  
};

console.log('Some random examples:');
for (let i = 0; i < 10; i++) {
  // An array of random length, full of random integers
  let arr = [ ...new Array(3 + Math.floor(Math.random() * 5)) ]
    .map(v => Math.floor(Math.random() * 4));
  
  // Show the result of `lowestFreqVal` on this random Array
  console.log(`lowestFreqVal(1, 1, ${JSON.stringify(arr)}) = ${lowestFreqVal(1, 1, arr)}`);
}

This approach may not be optimal, as it relies on using sort. It is recognized that finding the nth-maximal value in a list can be achieved with a faster runtime than sort (especially when n is small - logically, if n=0, a single pass (O(n)) suffices).

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

Determine selected option in Radio Button

FORM : <form id="approvalPenambahanUserInt" name="approvalPenambahanUserInt" action="" method="post"> <div class="form-group"> <div class="col-sm-12"> <label for= ...

Iterate through an object, with certain keys being duplicated

Currently, I am facing a scenario where the object I'm analyzing is quite messy... Essentially, within this object... my goal is to locate the pageviews node, but only if it has an array of data... Here's an example of the data: data = [ ...

Have you checked the console.log messages?

As a newcomer to web development, I hope you can forgive me if my question sounds a bit naive. I'm curious to know whether it's feasible to capture a value from the browser console and use it as a variable in JavaScript. For instance, when I enco ...

Using Vue.js to increment a value in an array every time a new row is added

In Vue.js, I am attempting to increment an array value when adding a new row. However, I encounter the following error message: You may have an infinite update loop in a component render function. The JavaScript logic looks like this: new Vue({ el: ...

Hiding the style tag in the head section of a Laravel-Vue.js application with Vue.js

Currently, I am working on a Laravel-Vue.js application. I have noticed that when Vue.js renders CSS, it appends some style tags in the HTML head as shown in the image below. Is there a way to hide these tags? My initial thought is that it can be achieved ...

How can I resolve a MySQL query error in Node.js that is throwing an undefined error?

There seems to be an issue with the second request returning undefined instead of showing the results. The expected behavior is that if the first request returns less than two lines, the second request should be executed. What could be causing this error ...

Executing pure JavaScript code in Grails using Groovy

this is a duplicate of Executing groovy statements in JavaScript sources in Grails with a slight variation, my intention is to only render the js-code without enclosing it in script tags picture someone loading a script from my server within their html l ...

Spinning the Prize message 90 degrees within the Lottery Wheel algorithm

I'm currently working on setting up a lucky draw spinning wheel for a page using the lottery-wheel package. Everything is functioning properly, but I've encountered an issue when adding more prizes to the wheel. The text of the prizes in each sec ...

Determining if a number exceeds 3 decimal points using AngularJS

I have encountered a problem where I need to determine if a value has more than three decimal places in AngularJS. Although I am familiar with checking if a value is a whole number or greater than zero, I am unsure how to perform this specific task. Below ...

What is the process for constructing an object that holds an array using literals?

Is there a way to create an object using literals like this? newObject.object[0].time = 1200; When attempting the following code, I encountered an error: var newObject = { object[0].time: 1200 }; Any insights on how to construct such objects using ...

Importing JavaScript files to work with Vue-Router: A Step-by-Step Guide

Seeking guidance on importing JavaScript files correctly throughout my Vue project, including within the components used to implement changes with Vue-Router. Currently, encountering an issue where I must reload the component in order for the JavaScript to ...

Debouncing in AngularJS with $watch

In my code, I have an HTML search field represented by the following: <input ng-model-options="{ debounce: 500 }" type="text" ng-model="name"> Along with the JavaScript snippet: $scope.$watch('name', function(newVal, oldVal) { ...

The request for data:image/png;base64,{{image}} could not be processed due to an invalid URL

I am facing an issue with converting image data that I receive from the server using Angular.js for use in ionic-framework. Here is the code snippet I have been working with: $http.post(link, { token: token, reservationCode: reservatio ...

Determine distinct items in an array that match a predefined criteria

I have a list of objects with two keys, img1 and img2. I need to identify unique objects based on the values of img1, while also retaining the corresponding value of img2. This is the current code I am using: const imgs_arr = [ ...new Set( inpu ...

Retrieving the Image of an Amazon Product using ASIN

My goal is to locate the image URLs for Amazon products using only their ASIN. For instance: This link pertains to a product with the ASIN B07NVVQL66 in the United States. Clicking on it will display an image of the product http://images.amazon.com/imag ...

What is the best way to have a TypeScript function return a class?

Currently, I am utilizing TypeScript alongside a dependency injection library that functions quite similarly to Angular 1 - essentially, you register a factory with your dependencies as arguments. Here is an example of how I would register a class using E ...

Is there a way to change the source attribute instead of the text content?

Is there a way to update the src attribute instead of the text content? For instance, if I want a winter image, title, and description for December, and a summer image, title, and description for August. How can I store images in this JSON format and use t ...

(perhaps) just a question regarding AJAX and PHP

Having a bit of trouble here - I have two files, main.html and processing.php. In the php file, I am trying to update a specific element on main.html, but I can't seem to retrieve either the html or javascript value from main.html For instance, main. ...

I recently started delving into React Native and am currently exploring how to implement custom fonts in my application. However, I have encountered an error that is preventing me from successfully integrating

The Issue: The error I encountered only appeared after including font-related code (such as importing from "expo-font" and using "AppLoading" from "expo", and utilizing the "Font.loadAsync()" function). Error: Element type is invalid: expected a string (fo ...

What is the method to establish a reference based on a value in programming?

Having some trouble setting the 'ref' of a TextInput from a value. Here's an example: var testtest = 'testvalue' <TextInput ref=testtest autoCapitalize="none" autoCorrect={false} autoFocus={false} placeholderTextColor="#b8b8b ...