【问题标题】:Choose array index by percentage按百分比选择数组索引
【发布时间】:2021-09-28 02:49:17
【问题描述】:

所以我想选择一个数组索引根据它在数组中的百分比。

“数组中的百分比”只是索引的函数,因此对于 11 元素数组,50% 的索引将是 5。

const numbers = [0 , 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];

我想我想首先通过获取数组的长度来获得一个可靠的数字来计算百分比。

numbers.length; // 14

虽然我将如何使用百分比进入数组,使用长度来选择 NEAREST 与百分比匹配的索引?例如,如果我想选择最接近数组 25% 的索引?

【问题讨论】:

  • 您需要确定“百分比”对您意味着什么。您需要遍历数组并为数组中的每个值计算这个“百分比”。然后你需要决定“最近”是什么意思。然后你需要找到与给定百分比“最接近”的百分比并获取它的索引。
  • @HereticMonkey 我可能是错的,但我认为“数组中的百分比”只是索引的函数,所以对于 11 元素数组来说,50%索引为 5。
  • @Pointy 这当然是对这句话的一种解释。我倾向于尽可能少地对其他人的问题做出假设。
  • 是的,就是这样@Pointy,你解释得更好,谢谢:D
  • @Harry 你可以而且应该edit你的问题来澄清它。

标签: javascript arrays sorting percentage


【解决方案1】:

我认为您正在寻找类似的东西。

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])

【讨论】:

  • 值得注意的是,Math.round() 的 ceil 号码将以 .5 结尾。
【解决方案2】:

您可以通过从数组的长度中减去 1,将其乘以百分比,最后计算结果来计算给定百分比的索引或值。

percentage 参数应该是介于 0.00 (0%) 和 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; }

【讨论】:

    【解决方案3】:

    我相信这就像通过从长度中获取所需的百分比来计算所需的索引一样清楚。

    const numbers = [0 , 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
    
    let desiredPercentage = 25;
    
    if (desiredPercentage) {
    
      let indexAtPercent = Math.floor(numbers.length * desiredPercentage / 100);
      
      if (indexAtPercent)
        indexAtPercent--;
        
      console.log(numbers[indexAtPercent]);
    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-01
      相关资源
      最近更新 更多