Array group by text based on certain character

I have been in a fight with an array which is similar to (original contains 5000+ elements):

[
    "Some Section  ⌄",
    "b",
    "c",
    "d",
    "e",
    "Some Other section  ⌄",
    "b",
    "c",
    "d",
    "x",
]

I want to produce an output that looks like:

[
	{
		"section": "Some Section", 
		"items":[ 
			"b",
    		"c",
    		"d",
    		"e"
    	]
	},
	{
		"section": "Some Other Section", 
		"items":[ 
			"b",
    		"c",
    		"d",
    		"x"
    	]
	},

]

So the "breaking point" or "grouping character" is the symbol. I tried to capture the index into a new array and then loop from index to index -1 etc. Whatever I attempt, I fail, does anyone have a magic trick up their sleeve ? I can no longer see it properly :')

This may work then..

let input = [
    "Some Section  ⌄",
    "b",
    "c",
    "d",
    "e",
    "Some Other section  ⌄",
    "b",
    "c",
    "d",
    "x",
]

let output = [] 
let obj
input.forEach(item => {    
    if (item.includes('⌄')){
        obj = {}
        obj.section = item.slice(0, -1).trim();
        obj.items = []
        output.push(obj)
    }
    else{
        obj.items.push(item)
    }
})
msg.payload = output
return msg;

I swear that I had something similar, but it did not want to function like yours, thanks a lot! Can finally move forward.

Just as it isn't protected against possible variations in incoming data, be prepared for errors :smiley:

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.