How to get only the first n% of an array in JavaScript?

JavascriptWeb DevelopmentObject Oriented Programming

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 ]
raja
Published on 20-Aug-2020 09:47:57
Advertisements