简体   繁体   中英

Grouping an array elements in Javascript

How can I group the following array if the subtraction of elements is less than 2?

var myarr = [1.7, 2, 1.4, 6, 7, 14, 15, 21,31,33.2,33.5]

And I want to have this result:

 var myarr = [[1.7, 2, 1.4], [6, 7], [14, 15], [21],[31,33.2,33.5]]

Reduce the array, and add a new sub array to the accumulator if the delta between the current and previous numbers is greater or equal to 2 (or it's the 1st number). Push the current number to the last array:

 var myarr = [1.7, 2, 1.4, 6, 7, 14, 15, 21,31,33.2,33.5] var result = myarr.reduce(function(r, n, i, arr) { if(i === 0 || Math.abs(n - arr[i - 1]) >= 2) r.push([]) r[r.length - 1].push(n) return r }, []); console.log(result)

I suggest to use the absolute value of the difference for checking with the wanted delta for inserting a new array in the result set, because the order of the values is not strictly ascending.

 var array = [1.7, 2, 1.4, 6, 7, 14, 15, 21, 31, 33.2, 33.5], delta = 2, grouped = array.reduce(function (r, v, i, a) { if (!i || Math.abs(a[i - 1] - v) > delta) { r.push([]); } r[r.length -1].push(v); return r; }, []); console.log(grouped);
 .as-console-wrapper { max-height: 100% !important; top: 0; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM