User User - 4 months ago 15
HTML Question

Create an associative array after .split ()

I take the example from the developer.mozilla.org official documentation so you can answer it more easily:

var names = "Harry Trump; Fred Barney; Helen Rigby; Bill Abel; Chris Hand";
var re = / \ s *; \ s * /;
var nameList = names.split (re);


This regular expression produces an array formed by the various elements divided by the character
;
.

My problem is this: I would like to associate with the array that is out of the element from which it was extracted, that is,
;
.
Basically the goal is to get something like this:

[
{
";": ["Harry Trump"]
},
{
";": ["Fred Barney"]
}
...
]


instead of

[ "Harry Trump", "Fred Barney" , ... ]


Would you like to tie them up?

Answer Source

If your separator is variable you can do this way

let names = "Harry Trump, Fred Barney, Helen Rigby, Bill Abel, Chris Hand"
let re = /\s*(,)\s*/
let res = names.split(re).map(
  (currentValue, index, array) => {
    if (index%2!=0) {
      return {
        [currentValue]: (array[index-1] )
      }          
    }
  }
)
.filter((n)=>n)
console.log(res)