So I wanted to choose an array index based off its percentage in the array.
The "percentage in the array" is just a function of the index, so like for an 11-element array the 50% index would be 5.
const numbers = [0 , 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
I imagine I'd want to first go ahead by grabbing the length of the array to have a solid number to work a percentage from.
numbers.length; // 14
Though how would I then go about using a percentage to go into the array using the length to select an index that NEAREST matches the percentage? For example if I wanted to select the index that was nearest to being on 25% of the array?
I think you are looking for something like this.
const numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
const percentage = 50
let indexAtPercentage = Math.round((numbers.length - 1) * percentage / 100)
console.log("index: " + indexAtPercentage + "\nnumber at index: " + numbers[indexAtPercentage])
You can calculate the index or value of a given percentage by subtracting one from the length of the array, multiplying it by the percentage, and finally flooring the result.
The percentage parameter should be a value between 0.00 (0%) and 1.00 (100%).
const
indexOfPercent = (arr, percent) => Math.floor((arr.length - 1) * percent),
valueOfPercent = (arr, percent) => arr[indexOfPercent(arr, percent)];
const numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
for (let i = 0; i < numbers.length; i++) {
const
percent = i / (numbers.length - 1),
index = indexOfPercent(numbers, percent),
value = valueOfPercent(numbers, percent);
console.log(`${i} ${percent.toFixed(2)} ${index} ${value}`);
}
.as-console-wrapper { top: 0; max-height: 100% !important; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With