Languages
[Edit]
EN

JavaScript - find max value skipping n found max values

6 points
Created by:
Cassia
1415

In this article, we would like to show how to find the n-th max number value in a number array using JavaScript.

The main idea in the presented solution is to use a special buffer array with candidates to store maximal detected number values and return only n-th maximal value from the buffer.

Using the below solution we are able to find:

  • maximal value (1st max),
  • second maximal value (2nd max),
  • third maximal value (3rd max),
  • and so on (n-th maximal value)

Practical example:

// ONLINE-RUNNER:browser;

const findIndex = (candidates, number) => {
	for (let j = 0; j < candidates.length; ++j) {
		const candidate = candidates[j];
		if (number > candidate) {
			return j;
		}
	}
	return null;
};

const findMax = (numbers, skip = 0) => {
	const limit = skip + 1;
  	if (limit > numbers.length) {  
		return null;
	}
	const candidates = [];
	for (let i = 0; i < limit; ++i) {
		const number = numbers[i];
		const index = findIndex(candidates, number);
		candidates.splice(index ?? candidates.length, 0, number);
	}
	for (let i = limit; i < numbers.length; ++i) {
		const number = numbers[i];
		const index = findIndex(candidates, number);
		if (index != null) {
			candidates.splice(index, 0, number);
			candidates.pop();
		}
	}
	return candidates[skip];
};


// Usage example:

const numbers = [2, 4, 3, 1];

console.log(findMax(numbers));     // 4      // normal max value searching
console.log(findMax(numbers, 1));  // 3      // max value searching with skipping 1 max value
console.log(findMax(numbers, 2));  // 2      // max value searching with skipping 2 max values
console.log(findMax(numbers, 3));  // 1      // max value searching with skipping 3 max values
console.log(findMax(numbers, 4));  // null   // we are not able to skip 4 max values because of numbers array length

 

See aslo

  1. TypeScript - find max value skipping n found max values 

Alternative titles

  1. JavaScript - find n-th max number value
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join