<万博manbetx平台> 指定值应插入到数组中的最低索引位置 sortedIndex – JavaScript 实用代码片段-万博manbetx平台

指定值应插入到数组中的最低索引位置 sortedIndex – JavaScript 实用代码片段

返回指定值应插入到数组中的最低索引位置,以保持其排序顺序。

检查数组是否按降序(松散地)排序。
使用 Array.findIndex() 来找到元素应该被插入的合适的索引位置。

const sortedIndex = (arr, n) => {
  const isDescending = arr[0] > arr[arr.length - 1];
  const index = arr.findIndex(el => (isDescending ? n >= el : n <= el));
  return index === -1 ? arr.length : index;
};
sortedIndex([5, 3, 2, 1], 4); // 1
sortedIndex([30, 50], 40); // 1

更多代码 JavaScript 实用代码片段 请查看 https://www.762w6o.com/30-seconds-of-code/

赞(0) 打赏
未经允许不得转载:万博manbetx平台 » 指定值应插入到数组中的最低索引位置 sortedIndex – JavaScript 实用代码片段

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

前端开发相关广告投放 更专业 更精准

联系我们

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏