首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何从一系列的价格值创建一系列的价格范围?

如何从一系列的价格值创建一系列的价格范围?
EN

Stack Overflow用户
提问于 2022-11-09 08:00:18
回答 4查看 75关注 0票数 0

我有一系列的价格

如果价格在2以内,我想把它们分类。

我如何做到这一点?

代码语言:javascript
复制
// present array
const array = [
   '3','5','6','12','17','22'
]

// the result I want
const array_ranges = [
   '3-6', '12',
  '17','22'
]
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2022-11-09 08:37:48

您可以定义2的偏移量,如果增量大于此偏移量,则检查最后一对值,并将新值推送到结果集,否则获取上次存储的第一部分的值或值,然后生成一个新的对。

代码语言:javascript
复制
const
    array = ['3','5','6','12','17','22'],
    offset = 2,
    result = array.reduce((r, v, i, a) => {
        if (!i || v - a[i - 1] > offset) r.push(v);
        else r.push(`${r.pop().split('-', 1)[0]}-${v}`);
        return r;
    }, []);

console.log(result);

票数 1
EN

Stack Overflow用户

发布于 2022-11-09 08:37:41

这里有一个不那么简洁的版本

代码语言:javascript
复制
const array = ['3', '5', '6', '12', '14', '17', '22'],
  rangeGap = 2,
  arrRange = array.reduce((acc, num) => {
    const range = acc.at(-1).split("-"), last = range.at(-1);
    if ((num - last) <= rangeGap) {
      if (range.length === 1) range.push(num); // new range
      else range[range.length-1] = num; // rewrite last slot
      acc[acc.length-1] = range.join("-"); // save the range
    } else acc.push(num);
    return acc;
  }, [array[0]]); // initialise with first entry
console.log(arrRange)

票数 2
EN

Stack Overflow用户

发布于 2022-11-09 10:26:16

一种可能的通用、可配置和可重用的方法是将还原器函数实现为函数语句,其中初始值是两个属性thresholdresult的对象,前者定义了范围值对其上/下一个范围值的容忍度或增量,后者以所有创建/收集的范围值为特征。

还原器确实处理了一个仅包含数字值的数组;因此,确保数字值的map任务只能在此之前执行。

代码语言:javascript
复制
function createAndCollectNumberRanges({ threshold, result }, current, idx, arr) {
  threshold = Math.abs(threshold);

  const previous = arr[idx - 1] ?? null;
  const next = arr[idx + 1] ?? null;

  if (
    previous === null ||
    previous < current - threshold
  ) {
    result.push(String(current));

  } else if (
    (next > current + threshold || next === null) &&
    previous >= current - threshold
  ) {
    result.push(`${ result.pop() }-${ current }`);
  }
  return { threshold, result };
}

console.log(
  ['3', '5', '6', '12', '17', '22']
    .map(Number)
    .reduce(createAndCollectNumberRanges, {

      threshold: 2,
      result: [],

    }).result
);
console.log(
  ['0', '3', '5', '6', '12', '14', '15', '17', '22', '23']  
    .map(Number)
    .reduce(createAndCollectNumberRanges, {

      threshold: 2,
      result: [],

    }).result
);

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74371571

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档