# Finding degree of subarray in an array JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

#### JavaScript for beginners

Best Seller

74 Lectures 10 hours

#### Modern Javascript for Beginners + Javascript Projects

Most Popular

112 Lectures 15 hours

#### The Complete Full-Stack JavaScript Course!

Best Seller

96 Lectures 24 hours

The degree of an array of literals is defined as the maximum frequency of any one of its elements.

const arr = [1, 2, 3, 3, 5, 6, 4, 3, 8, 3];

The degree of this array is 4, because 3 is repeated 4 times in this array.

We are required to write a JavaScript function that takes in an array of literals. The task of our function is to find the length of the smallest continious subarray from the array whose degree is same as of the whole array.

## Example

const arr = [1, 2, 3, 3, 5, 6, 4, 3, 8, 3];
const findShortestSubArray = (arr = []) => {
let range = new Map(), maxDegree = 0, minLength = Infinity;
for(let i = 0; i < arr.length; i++){ if(range.has(arr[i])) {
let start = range.get(arr[i]);
let degree = range.get(arr[i]); degree++;
range.set(arr[i], [start, i, degree]);
if(degree > maxDegree)
maxDegree = degree;
}
else {
let degree = 1;
range.set(arr[i],[i, i, degree]); if(degree > maxDegree)
maxDegree = degree;
}
}
for (let key of range.keys()){
let val = range.get(key)
if(val === maxDegree){
let diff = (val - val) + 1;
if(diff < minLength) minLength = diff;
}
}
return minLength;
};
console.log(findShortestSubArray(arr));

## Output

And the output in the console will be −

8