# Taking part from array of numbers by percent JavaScript

We have an array of Number literals like this −

const numbers = [10,6200,20,20,350,900,26,78,888,10000,78,15000,200,1280,2000,450];

We are supposed to write a function that takes an array of numbers and a number between [0, 100], basically this number represents a certain percent. Let us denote this number by x for now.

Now we have to return a subarray of first n elements of the original array that add up equal to or just less than the x % of the total sum of all array elements.

Take a simpler example −

const numbers = [12, 10, 6, 8, 4, 2, 8];

For this array total sum is 50, and now if we provide say 25 as the second argument (the value for x), then we have to return the first n elements that add up to just equal or less than 25% of 50 which is in fact 12.5.

So in this case an array with only the first element should be returned because adding the second element (10) to 12 would exceed out threshold value (12.5).

Let’s write the code for this. At first, we simply reduce the array to its sum then in a for loop we construct an array that matches the criteria mentioned above −

## Example

const numbers =
[10,6200,20,20,350,900,26,78,888,10000,78,15000,200,1280,2000,450];
const findPercent = (arr, percent) => {
const sum = arr.reduce((acc, val) => acc+val);
const part = [];
let curr = 0;
for(let i = 0; i < arr.length; i++){
curr += arr[i];
if(curr <= (sum*percent)/100){
part.push(arr[i]);
} else {
break;
};
};
return part;
};
console.log(findPercent(numbers, 35));
console.log(findPercent(numbers, 5));
console.log(findPercent(numbers, 65));
console.log(findPercent(numbers, 95));

## Output

The output in the console will be −

[
10, 6200, 20, 20,
350, 900, 26, 78,
888
]
[ 10 ]
[
10, 6200, 20,
20, 350, 900,
26, 78, 888,
10000, 78
]
[
10, 6200, 20, 20,
350, 900, 26, 78,
888, 10000, 78, 15000,
200, 1280
]

Updated on: 24-Aug-2020

970 Views