我有一系列的价格
如果价格在2以内,我想把它们分类。
我如何做到这一点?
// present array
const array = [
'3','5','6','12','17','22'
]
// the result I want
const array_ranges = [
'3-6', '12',
'17','22'
]发布于 2022-11-09 08:37:48
您可以定义2的偏移量,如果增量大于此偏移量,则检查最后一对值,并将新值推送到结果集,否则获取上次存储的第一部分的值或值,然后生成一个新的对。
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);
发布于 2022-11-09 08:37:41
这里有一个不那么简洁的版本
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)
发布于 2022-11-09 10:26:16
一种可能的通用、可配置和可重用的方法是将还原器函数实现为函数语句,其中初始值是两个属性threshold和result的对象,前者定义了范围值对其上/下一个范围值的容忍度或增量,后者以所有创建/收集的范围值为特征。
还原器确实处理了一个仅包含数字值的数组;因此,确保数字值的map任务只能在此之前执行。
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
);
https://stackoverflow.com/questions/74371571
复制相似问题