'How can I make a new array from a event emitter ( gives bytes array), where new arrays first element will be '10' and last '13'?
I have incoming bytes of arrays once a time. It kind of looks like this
[10,12,34,58,62]
[83,33,23,44,13]
[10,12,34,58,62]
[34, 77,54,23,87]
[83,33,23,44,13]
[10,12,34,58,62]
[83,33,23,44,66]
[13] …continues.
So, it renders each array every time. I needed them to be rendered like
[10,12,34,58,62,83,33,23,44,13]
[10,12,34,58,62,34,77,54,23,87,83,33,23,44,13]
[10,12,34,58,62,83,33,23,44,66,13].
The first element will be 10 and the last 13. Can anyone help me with the code? Thanks in advance.
Solution 1:[1]
If your incoming bytes is 2d array then try this.
let arr = [
[10, 12, 34, 58, 62],
[83, 33, 23, 44, 13],
[10, 12, 34, 58, 62],
[34, 77, 54, 23, 87],
[83, 33, 23, 44, 13],
[10, 12, 34, 58, 62],
[83, 33, 23, 44, 66],
[13]
]
let openedArr = []
for (let value of arr) {
openedArr = [...openedArr, ...value]
}
let resultArr = []
let child = []
for (let value of openedArr) {
child.push(value)
if (value == 13) {
resultArr.push(child)
child = []
}
}
console.log(resultArr)
Explaination
- Make an new array by spreading all incoming array.
- Create two arrays resultArr and Child Array
- Push every array elements to Child array
- If there is 13, then push child array to resultArr, and empty child array.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Masood Alam |
