- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 ]
- Related Articles
- How to get the first n values of an array in JavaScript?
- How to get only the first BOT ID from thes JavaScript array?
- Constructing an array of first n multiples of an input number in JavaScript
- How to get the first element of an array in PHP?
- Get only specific values in an array of objects in JavaScript?
- Get the max n values from an array in JavaScript
- Get the first element of array in JavaScript
- How to get only first word of object's value – JavaScript?
- Get the first and last item in an array using JavaScript?
- Get average of every group of n elements in an array JavaScript
- JavaScript function to take a number n and generate an array with first n prime numbers
- How to get the only current year in JavaScript?
- Getting only the first item for an array property in MongoDB?
- Sort an array to have specific items first in the array - JavaScript
- How to get the first index of an occurrence of the specified value in a string in JavaScript?

Advertisements