Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create new array and push into another in forEach() (JS)

I have an object and i want to sort the items inside via forEach().

Each fifth element should be stored in a new array.

let content = []
let index = 0
Obj.forEach(function(item) {
    if(item.includes('<h2>') && index !== 0) {
        index++
    }
    content[index].push(item)
})

Unfortunately, i cannot push into content[index].push(item)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How i can create a new array, push new values and start a new array when my if is true?

>Solution :

You can use nullish coalescing assignment to create an array if it doesn’t already exist.

(content[index] ??= []).push(item);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading