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
How to get only the first n% of an array in JavaScript?
We are required to write a function that takes in an array arr and a number n between 0 and 100 (both inclusive) and returns the n% part of the array. Like if the second argument is 0, we should expect an empty array, complete array if it's 100, half if 50, like that.
And if the second argument is not provided it should default to 50. Therefore, the code for this will be ?
Syntax
const byPercent = (arr, n = 50) => {
const requiredLength = Math.floor((arr.length * n) / 100);
return arr.slice(0, requiredLength);
};
Parameters
arr: The input array from which to extract the percentage.
n: The percentage (0-100) of elements to return. Defaults to 50 if not provided.
How It Works
The function calculates the required length by multiplying array length with the percentage and dividing by 100. Math.floor() ensures we get a whole number of elements. Then slice(0, requiredLength) extracts the first n% elements.
Example
const numbers = [3,6,8,6,8,4,26,8,7,4,23,65,87,98,54,32,57,87];
const byPercent = (arr, n = 50) => {
const { length } = arr;
const requiredLength = Math.floor((length * n) / 100);
return arr.slice(0, requiredLength);
};
console.log("50% (default):", byPercent(numbers));
console.log("84%:", byPercent(numbers, 84));
console.log("34%:", byPercent(numbers, 34));
console.log("0%:", byPercent(numbers, 0));
console.log("100%:", byPercent(numbers, 100));
50% (default): [ 3, 6, 8, 6, 8, 4, 26, 8, 7 ] 84%: [ 3, 6, 8, 6, 8, 4, 26, 8, 7, 4, 23, 65, 87, 98, 54 ] 34%: [ 3, 6, 8, 6, 8, 4 ] 0%: [] 100%: [ 3, 6, 8, 6, 8, 4, 26, 8, 7, 4, 23, 65, 87, 98, 54, 32, 57, 87 ]
Edge Cases
// Empty array
console.log("Empty array:", byPercent([], 50));
// Small array with percentage
const small = [1, 2, 3];
console.log("33% of 3 elements:", byPercent(small, 33));
console.log("67% of 3 elements:", byPercent(small, 67));
Empty array: [] 33% of 3 elements: [ 1 ] 67% of 3 elements: [ 1, 2 ]
Conclusion
This function efficiently extracts a percentage of array elements using Math.floor() for length calculation and slice() for extraction. It handles edge cases like empty arrays and provides a sensible default of 50%.
