我有一系列價格
如果這些價格在 2 以內,我想將它們分組
我如何實作這一目標
// present array
const array = [
'3','5','6','12','17','22'
]
// the result I want
const array_ranges = [
'3-6', '12',
'17','22'
]
uj5u.com熱心網友回復:
這是更長的腳本 - 至少它更具可讀性。
const array = ['3', '5', '6', '12', '14', '17', '22'];
const arrRange = array.reduce((acc, num, i) => {
if (i === 0) {
acc.push(num);
return acc;
}
let range = acc[acc.length - 1].split("-");
const last = range[range.length - 1];
if ((num - last)<=2) {
if (range.length === 1) range.push(num)
else range[range.length - 1] = num;
acc[acc.length - 1] = range.join("-")
} else acc.push(num);
return acc;
}, []);
console.log(arrRange)
uj5u.com熱心網友回復:
您可以定義一個偏移量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);
uj5u.com熱心網友回復:
一種可能的通用、可配置和可重用的方法是將 reducer 函式實作為函式陳述句,其中初始值是兩個屬性的物件,threshold前者result定義范圍值的容差或與其上一個/下一個范圍值的差值,后者定義具有所有創建/收集的范圍值。
reducer 確實處理了一個只有數字值的陣列;因此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://www.uj5u.com/qiye/530671.html
