Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
79 views
in Technique[技术] by (71.8m points)

javascript - Building an array of sequential numbers

i have an incoming array:

[{step: 0, count: 1}, {step: 1, count: 5}, {step: 5, count: 5}] 

so i need to transform incoming array in another array

[0, 1, 2, 3, 4, 5, 10, 15, 20, 25, 30]

I have tried to go this way:

const convertRangeData = (rangeData) =>
  {
  const convertedRangeData =
    rangeData.reduce( (acc, item) => 
        {
        const { step, count } = item;
        const prev                 = acc[acc.length - 1];
        return [...acc, ...[...Array(count)].fill(step).map((i, idx) => i * (idx + 1) + prev)];
        },[0] )
    return convertedRangeData;
  }

but I've got

[0, 0, 1, 2, 3, 4, 5, 10, 15, 20, 25, 30]
question from:https://stackoverflow.com/questions/65849430/building-an-array-of-sequential-numbers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use Array.from() to create an array with values in the ranges. Then iterate the array of ranges.

To create the continuous ranges reduce the array of ranges. When creating a range take the last number from the accumulator (acc), and use it as the start value.

const range = ({ step, count }, start = 0) => 
  Array.from({ length: count }, (_, i) => (i + 1) * step + start)
  
const continuousRange = arr =>
  arr.reduce((acc, r) => acc.concat(range(r, acc[acc.length -1])), [])

const ranges = [{step: 0, count: 1}, {step: 1, count: 5}, {step: 5, count: 5}]

const result = continuousRange(ranges)

console.log(result)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...