Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - 筛选值数组并将其分组(Filter an Array of Values and group them)

I have an array that i need to sort and put values that are too similar together in another array.(我有一个数组,我需要对太相似的值进行排序并将其放到另一个数组中。)

eg(例如) function group (arrData) { for (let i = 0; i < array.length - 1; i++) { if ( (array[i + 1] - array[i] ) < 5) { return array[i]; } } } const arr = [1,15,16,33,35,37,55,58] const newArr = arr.map((item,index,array) => group(array)); but it returns only one value.(但它只返回一个值。) How do i fix this?(我该如何解决?) as for desired output : [[15,16],[33,35,36],[55,58]](至于所需的输出:[[15,16],[33,35,36],[55,58]])   ask by dobbey translate from so

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

1 Answer

0 votes
by (71.8m points)

You could sort the array, if not in ascending order and then reduce this array by checking the actual value and the predecessor.(您可以对数组进行排序(如果不按升序排列),然后通过检查实际值和前一数组来缩小该数组。)

If the dela is greater or equal 5 or if youi got the first value of the array, then push an empty array to the result set.(如果dela大于或等于5或者您获得了数组的第一个值,则将空数组推入结果集。) Then push the value to the last array in the result set.(然后将值推到结果集中的最后一个数组。) var array = [1, 15, 16, 33, 35, 37, 55, 58], result = array .sort((a, b) => a - b) // not necessary with sorted data .reduce((r, v, i, a) => { if (!i || v - a[i - 1] >= 5) r.push([]); r[r.length - 1].push(v); return r; }, []); console.log(result);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...