Home > Blockchain >  How to replicate the pandas explode() functionality with Javascript?
How to replicate the pandas explode() functionality with Javascript?

Time:10-10

I'm automating my google sheets in app scripts. I came across a scenario where one cell has multiple values. I want to explode it as in python.

Example input and output:

input = [["Hi",12,"One line
two line
three line", "God"],["Bye",13,"check","man"]]
output = [["Hi",12,"One line","God"],["Hi",12,"two line","God"],["Hi",12,"Three line","God"],["Bye",13,"check","man"]]

Following is my partial attempt

var final = y.map(r => {
    return r.map(x => {
      if(x.toString().indexOf("/n") > -1)
      {
        x = x.toString().split("/n");
      }
      return x;      
      });
  });

CodePudding user response:

Use reduce to loop: split the string by new line \n, map the split array and join it to the parent row and the previous accumulator and flat.

/*<ignore>*/console.config({maximize:true,timeStamps:false,autoScroll:false});/*</ignore>*/ 

const input = [["Hi",12,"One line\ntwo line\nthree line", "God"],["Bye",13,"check","man"]];
const output = input.reduce((acc,[a,b,c],i) =>  [acc,c.split("\n").map(sc => [a,b,sc])].flat() ,[]);
console.log(output);
<!-- https://meta.stackoverflow.com/a/375985/ -->    <script src="https://gh-canon.github.io/stack-snippet-console/console.min.js"></script>

  • Related