JavaScript. Have an array of objects
0:{mask: "202 203, 287 376, 412 162, 381 121", add: 1}
1:{mask: "108 511, 247 291, 151 186, 97 180", add: 1}
2:{mask: "147 202, 289 234, 268 113", add: 0}
3:{mask: "79 225, 318 374, 443 212, 359 118", add: 1}
4:{mask: "116 253, 327 351, 377 198, 361 171", add: 1}
5:{mask: "232 237, 288 566, 406 481, 458 240, 421 188", add: 0}
6:{mask: "222 391, 361 298, 347 170", add: 0}
Need to split they to arrays with add = 1
and few add = 0
after, before next add = 1
, with preservation of order like this
ar1 = [
0: {mask: "202 203, 287 376, 412 162, 381 121", add: 1}
]
ar2 = [
0: {mask: "108 511, 247 291, 151 186, 97 180", add: 1}
1: {mask: "147 202, 289 234, 268 113", add: 0}
]
ar3 = [
0: {mask: "79 225, 318 374, 443 212, 359 118", add: 1}
]
ar4 = [
0: {mask: "116 253, 327 351, 377 198, 361 171", add: 1}
1: {mask: "232 237, 288 566, 406 481, 458 240, 421 188", add: 0}
2: {mask: "222 391, 361 298, 347 170", add: 0}
]
it can be array of objects (with array inside) doesn't matter, the main thing is group element with add = 1
with all next elements, that have add = 0
Reduce can help you although it's a trick. Your can adopt a for loop if you don't like reduce
const arr = [{mask: "202 203, 287 376, 412 162, 381 121", add: 1}, {mask: "108 511, 247 291, 151 186, 97 180", add: 1}, {mask: "147 202, 289 234, 268 113", add: 0}, {mask: "79 225, 318 374, 443 212, 359 118", add: 1}, {mask: "116 253, 327 351, 377 198, 361 171", add: 1}, {mask: "232 237, 288 566, 406 481, 458 240, 421 188", add: 0}, {mask: "222 391, 361 298, 347 170", add: 0}]; const result = []; arr.reduce((a,b) => { if (a === null || b.add == 1) result.push([]); result[result.length-1].push(b); return b },null) console.log(result);
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.