簡體   English   中英

nodejs - 值差大於 2 的單獨數組

[英]nodejs - separate array with value difference greater than 2

是否可以將值差大於 2 的單獨數組分開

[
  '6',   '7',   '8',   '9',   '10',  '11',  '12',  '13',  '14',
  '15',  '16',  '31',  '32',  '33',  '34',  '35',  '36',  '37',
]

我想這樣分開

 [ '6',   '7',   '8',   '9',   '10',  '11',  '12',  '13',  '14', '15',  '16']
 [ '31',  '32',  '33',  '34',  '35',  '36',  '37']

你可以試試這樣的

 "use strict"; const array = [1, 2, 3, 4, 5, 7, 8, 10, 11, 12, 13, 14]; function detectAnomalies(array) { const results = []; let lastValue = null; let currentSeries = []; for (const currentValue of array) { if (lastValue === null) { lastValue = currentValue; } if (Math.abs(currentValue - lastValue) >= 2) { results.push(currentSeries); currentSeries = []; } currentSeries.push(currentValue); lastValue = currentValue; } results.push(currentSeries); return results; } console.log(detectAnomalies(array));

此外,展示您嘗試過的內容總是很好:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM