![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
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(byPercent(numbers)); console.log(byPercent(numbers, 84)); console.log(byPercent(numbers, 34));
Output
The output in the console will be −
[ 3, 6, 8, 6, 8, 4, 26, 8, 7 ] [ 3, 6, 8, 6, 8, 4, 26, 8, 7, 4, 23, 65, 87, 98, 54 ] [ 3, 6, 8, 6, 8, 4 ]
Advertisements