Sorting an Array and Extracting the top k Elements
In this approach, the unsorted array of integers is sorted in non-ascending order, from highest to lowest in JavaScript. Once the array is sorted, the top k elements are extracted by selecting the first k elements of the sorted array. Sorting the array allows for easy identification of the top aspects, as they are positioned at the beginning of the sorted array.
Example: The below example uses the sort method to sort an array of numbers in descending order and returns the top ‘k’ elements.
function topKElementsSorting(arr, k) {
arr.sort((a, b) => b - a);
return arr.slice(0, k);
}
// Example
const arr = [3, 1, 4, 2, 3, 4, 4];
const k = 3;
console.log("Top", k, "elements:",
topKElementsSorting(arr, k));
Output
Top 3 elements: [ 4, 4, 4 ]
JavaScript Program to Find Top k Elements
Given an array, our task is to find the top k elements in an unsorted array of integers in JavaScript, either the largest or the smallest. Duplicate values may be in the array. The output will be a new array with the top k elements arranged in a non-ascending order (from largest to smallest).
Table of Content
- Sorting an Array and Extracting the top k Elements
- Using a Max Heap
- Using Quickselect algorithm
Contact Us