Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Top n max value from array of object JavaScript
Finding the top n objects with maximum values from an array is a common programming task. Let's explore how to get objects with the highest duration values from an array of objects.
Problem Statement
Given an array of objects, we need to create a function that returns the top n objects based on the highest duration values.
const arr = [
{"id":0,"start":0,"duration":117,"slide":4,"view":0},
{"id":0,"start":0,"duration":12,"slide":1,"view":0},
{"id":0,"start":0,"duration":41,"slide":2,"view":0},
{"id":0,"start":0,"duration":29,"slide":3,"view":0},
{"id":0,"start":0,"duration":123,"slide":3,"view":0},
{"id":0,"start":0,"duration":417,"slide":2,"view":0},
{"id":0,"start":0,"duration":12,"slide":1,"view":0},
{"id":0,"start":0,"duration":67,"slide":2,"view":0}
];
console.log("Original array length:", arr.length);
Original array length: 8
Solution Using Sort and Slice
The most straightforward approach is to sort the array by duration in descending order and then slice the first n elements.
const topN = (arr, n) => {
if(n > arr.length){
return false;
}
return arr
.slice()
.sort((a, b) => {
return b.duration - a.duration
})
.slice(0, n);
};
// Test with different values of n
console.log("Top 3 objects:");
console.log(topN(arr, 3));
console.log("\nTop 4 objects:");
console.log(topN(arr, 4));
console.log("\nTop 5 objects:");
console.log(topN(arr, 5));
Top 3 objects:
[
{ id: 0, start: 0, duration: 417, slide: 2, view: 0 },
{ id: 0, start: 0, duration: 123, slide: 3, view: 0 },
{ id: 0, start: 0, duration: 117, slide: 4, view: 0 }
]
Top 4 objects:
[
{ id: 0, start: 0, duration: 417, slide: 2, view: 0 },
{ id: 0, start: 0, duration: 123, slide: 3, view: 0 },
{ id: 0, start: 0, duration: 117, slide: 4, view: 0 },
{ id: 0, start: 0, duration: 67, slide: 2, view: 0 }
]
Top 5 objects:
[
{ id: 0, start: 0, duration: 417, slide: 2, view: 0 },
{ id: 0, start: 0, duration: 123, slide: 3, view: 0 },
{ id: 0, start: 0, duration: 117, slide: 4, view: 0 },
{ id: 0, start: 0, duration: 67, slide: 2, view: 0 },
{ id: 0, start: 0, duration: 41, slide: 2, view: 0 }
]
How It Works
The function works in four steps:
- Validation: Check if n exceeds array length
-
Copy: Use
slice()to create a copy and avoid mutating the original array -
Sort: Sort by duration in descending order using
b.duration - a.duration -
Extract: Use
slice(0, n)to get the first n elements
Alternative Approach with Error Handling
const getTopNWithValidation = (arr, n, property = 'duration') => {
if (!Array.isArray(arr)) {
throw new Error('First argument must be an array');
}
if (n <= 0) {
return [];
}
if (n > arr.length) {
console.warn(`Requested ${n} items but array only has ${arr.length} items`);
n = arr.length;
}
return arr
.slice()
.sort((a, b) => b[property] - a[property])
.slice(0, n);
};
// Test with edge cases
console.log("Top 10 (more than available):");
console.log(getTopNWithValidation(arr, 10));
console.log("\nTop 0:");
console.log(getTopNWithValidation(arr, 0));
Top 10 (more than available):
[
{ id: 0, start: 0, duration: 417, slide: 2, view: 0 },
{ id: 0, start: 0, duration: 123, slide: 3, view: 0 },
{ id: 0, start: 0, duration: 117, slide: 4, view: 0 },
{ id: 0, start: 0, duration: 67, slide: 2, view: 0 },
{ id: 0, start: 0, duration: 41, slide: 2, view: 0 },
{ id: 0, start: 0, duration: 29, slide: 3, view: 0 },
{ id: 0, start: 0, duration: 12, slide: 1, view: 0 },
{ id: 0, start: 0, duration: 12, slide: 1, view: 0 }
]
Top 0:
[]
Key Points
- Always use
slice()before sorting to avoid mutating the original array - The sort comparator
(a, b) => b.duration - a.durationsorts in descending order - Handle edge cases like n being greater than array length or zero
- The function can be made generic by accepting the property name as a parameter
Conclusion
Using sort and slice is the most readable approach for getting top n objects by a numeric property. The key is to create a copy first, sort by the desired property in descending order, then extract the required number of elements.
Advertisements
