在 javascript 中尋找一些幫助。問題來了
這是我的輸入:
[
{channel: 471, unit: 1},
{channel: 472, unit: 2},
{channel: 473, unit: 3},
{channel: 474, unit: 5},
{channel: 479, unit: 6}
]
這是我正在尋找的輸出:
Ch: 471-474, 479 #1-3,5-6
所以基本上回圈遍歷物件陣列以排序的方式匯總數值。我最初使用math.max()andmath.min()方法來查找最大和最小數字以顯示如下:
Ch: 471-479
但這并沒有說明沒有 475,476,477 或 478 的事實。我還使用 Object.keys() 方法將物件轉換為陣列,然后通過使用math.max和進行過濾min
知道我將如何做這樣的事情嗎?甚至有可能嗎?任何幫助表示贊賞!
為了徹底起見,這是到目前為止我被卡住的整個代碼
const regex = /Ch (?<channel>\d ): (?<position>(?:\w|\s) ) #(?<units>\d )/g;
const inputString = "Ch 471: PRO BM R #5,Ch 472: PRO BM R #4,Ch 473: PRO BM R #3,Ch 481: PRO BM L #5,Ch 482: PRO BM L #4,Ch 484: PRO BM L #3";
const groups = {};
[...inputString.matchAll(regex)].forEach(a => (groups[a.groups.position] ||= []).push({ channel: a.groups.channel, units: a.groups.units }));
console.log(groups);
const keys = Object.keys(groups);
console.log(keys)
keys.forEach((key,index)=>{
let maxChannelNum = Math.max.apply(Math, groups[key].map(function(x) {return x.channel;}))
let minChannelNum = Math.min.apply(Math, groups[key].map(function(x) {return x.channel;}))
let maxUnitNum = Math.max.apply(Math, groups[key].map(function(x) {return x.units;}))
let minUnitNum = Math.min.apply(Math, groups[key].map(function(x) {return x.units;}))
console.log(`Ch: ${minChannelNum}-${maxChannelNum} ${key} #${minUnitNum}-${maxUnitNum}`)
})
uj5u.com熱心網友回復:
首先,您需要明確定義您希望如何準確地顯示您的數字范圍以及每個數字之間的最小間隔是多少 - 例如,如果您期望浮點數的可能性(例如,471、472、472.5、 473...),你必須重新定義什么算作區間的一部分(例如 471-473)以及什么打破區間(在上述情況下,這將是 475)。
只要您可以定義什么算作范圍的一部分,以及您需要在什么時候開始一個新的范圍,我認為沒有什么能阻止您采用根據資料對所有資料集進行簡單排序的天真方法價值; 在這種情況下,給你兩套
471, 472, 473, 474, 479
和
1, 2, 3, 5, 6
然后簡單地回圈遍歷它們,選擇每個資料集的第一個條目作為范圍的開始,并在它打破范圍的條件后定義范圍的結束 - 在這種情況下,比前面的數字大超過一。
我確信有更多最佳方法可以實作這一目標,但是有什么可以直接反對這種方法的嗎?
uj5u.com熱心網友回復:
您可以獲取所有數字,組合連續數字并將它們連接到字串。
const
update = (array, value) => {
const
last = array[array.length - 1],
lastValue = last?.[1] || last?.[0];
if (lastValue 1 === value) last[1] = value;
else array.push([value]);
},
input = "Ch 471: PRO BM R #5,Ch 472: PRO BM R #4,Ch 473: PRO BM R #3,Ch 481: PRO BM L #5,Ch 482: PRO BM L #4,Ch 484: PRO BM L #3",
temp = input
.split(',')
.map(s => s.match(/\d /g))
.reduce((r, [a, b]) => {
update(r[0], a);
update(r[1], b);
return r;
}, [[], []])
.map(a => a.map(b => b.join('-')).join()),
result = `Ch: ${temp[0]} #${temp[1]}`
console.log(result);
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/397333.html
標籤:javascript 数组 目的 数学
