Home > Net >  Converting a string to Matrix to be displayed using a table
Converting a string to Matrix to be displayed using a table

Time:06-10

I recently came across a problem where I needed to take a string like this one. "5.0, 100, 5.5, 101, 6.0, 102:L10;5.0, 99, 5.5, 100, 6.0, 101:L20" and convert it to a matrix to then be shown as a table. The matrix would look something like this:

L10 L20
5.0 100 99
5.5 101 100
6.0 102 100

I know to start that I could use split() to break the string into different arrays by looking at the ,, :, and ; but I was a little stuck on how to get it to where I could easily use the data to put it into a table. I got to where I had it broken into this:

[ ["5.0", "100", "5.5", "101", "6.0", "102"], ["L10"], ["5.0", "99", "5.5", "100", "6.0", "101"], ["L20"] ]

I got here with the following code.

var input = "5.0, 100, 5.5, 101, 6.0, 102:L10;5.0, 99, 5.5, 100, 6.0, 101:L20"

function test(){
    
    let firstSplit = input.split(';');
  
  let secondSplit = [];
  let thirdSplit = [];
      
      firstSplit.forEach((item) => {
   
    let splitArray = item.split(':')
    secondSplit.push(splitArray)
  })
  
  
  secondSplit.forEach((array) => {
   let split2 = array.forEach((item) => {
     let secondSplit = item.split(',')
     thirdSplit.push(secondSplit)
   })
   
    
   
  } )
  return thirdSplit;
}

console.log(test());

I would greatly appreciate any help in figuring this out!

CodePudding user response:

Is this what you want (sorry for online):

function parse(s)
{
    let r = {};
    s.split(';').map(e => { e = e.split(':'); r[e[1].trim()] = e[0].split(/(. ?,. ?,)/).map(e => e.trim()).filter(e => e).reduce((a,e,i)=>{ e = e.split(',').map(e=>e.trim()); a[e[0]] = e[1]; return a; }, {}) })
    return r;
}

var result = parse('5.0, 100, 5.5, 101, 6.0, 102:L10;5.0, 99, 5.5, 100, 6.0, 101:L20');

console.log(result['L10']['5.5']); // Return '101'
console.log(result['L20']['5.0']); // Return '99'

CodePudding user response:

It's not elegant, but it works out so that you have an object that has all the values you need, like so:

{points: Array(3), L10: Array(3), L20: Array(3)}

const tablestring = "5.0, 100, 5.5, 101, 6.0, 102:L10;5.0, 99, 5.5, 100, 6.0, 101:L20"
const obj = {
    points : []
}

const s2 = tablestring.split(';')
const s22 = s2.map(s => s.split(':'));

for(let arr of s22){
    obj[arr[1]] = []
}

const s222 = s22.map((curr) => curr[0].split(','))

s22.map(curr => {
  curr[0].split(',')
    .map((val, idx) => 
      idx % 2 === 0
      ? !obj['points'].some(exists => exists === val) && obj['points'].push(val)
      : obj[curr[1]].push(val)
)})

console.log(obj)

CodePudding user response:

Parse your data

Here's how I'd create a much more usable data format:

const str = "5.0, 100, 5.5, 101, 6.0, 102:L10;5.0, 99, 5.5, 100, 6.0, 101:L20";

const data = {};
str.split(/;/)
  .map(row => row.split(/:/))
  .forEach(([row, key]) => {
    row.match(/[^, ] , [^, ] /g)
      .map(r => r.split(/, /))
      .forEach(([item, value]) => data[item] = { ...(data[item] || {}), [key]: value });
  });

console.log(data);

It transforms your data in this form:

{
  "5.0": {
    "L10": "100",
    "L20": "99"
  },
  "5.5": {
    "L10": "101",
    "L20": "100"
  },
  "6.0": {
    "L10": "102",
    "L20": "101"
  }
}

Present your data

And here's how you could manipulate it to create an HTML table:

const str = "5.0, 100, 5.5, 101, 6.0, 102:L10;5.0, 99, 5.5, 100, 6.0, 101:L20";

const data = {};
str.split(/;/)
  .map(row => row.split(/:/))
  .forEach(([row, key]) => {
    row.match(/[^, ] , [^, ] /g)
      .map(r => r.split(/, /))
      .forEach(([item, value]) => data[item] = { ...(data[item] || {}), [key]: value });
  });

// everything below is only to create a proper HTML table

const headers = str.match(/(?<=:)([^\s;] )/g);

document.body.querySelector('thead').append(document.createElement('th'), ...headers.map(header => elem('th', header)));
document.body.querySelector('tbody').append(...Object.entries(data).map(([item, props]) => row(item, ...headers.map(header => props[header]))));

function elem(type = 'td', text) {
  const e = document.createElement(type);
  e.innerText = text;
  return e;
}

function row(...items) {
  const r = document.createElement('tr');
  r.append(...items.map(item => elem('td', item)));
  return r;
}
table {
  font-family: sans-serif;
  background: #eee;
}

td {
  padding: 2px .5em;
}

td:first-child {
  font-weight: bold;
}
<table>
  <thead></thead>
  <tbody></tbody>
</table>

  • Related