简体   繁体   中英

Split array of numbers into 9 arrays

I have an array such as:

[ 3, 6, 12, 16, 26, 36, 37, 42, 54, 59, 61, 68, 71, 83, 88 ]

I would like split into 9 different arrays based on ranges 1-9, 10-19, 20-29, 30-39, 40-49, 50-59, 60-69, 70-79, 80-90.

Just like a 1-90 bingo card would be set up.

What is the best way to do this with Javascript?

You could take the value of the division by 10 as index and collect the values. To avoid to add 90 to a new slot, you could take a minimum as index and adjust the index.

 var array = [3, 6, 12, 16, 26, 36, 37, 42, 54, 59, 61, 68, 71, 83, 88, 90], result = array.reduce( (r, v) => (r[Math.min(8, Math.floor(v / 10))].push(v), r), Array.from({ length: 9 }, _ => []) ); console.log(result);
 .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