0

I need to combine 2 arrays read from an excel file into 2-dimensional array, so I can place it as dataSource of material table.

I have these 2 arrays read from excel using XLSX library:

    reader.onload = (e) => {
      const res = reader.result as string; // This variable contains your file as text
      const lines = res.split('\n'); // Splits you file into lines
      let ids=[];
      let name = [];
      let array:any[][];
      lines.forEach((line, index) => {
        //console.log(line);
        ids.push((line.split(',')[0]));
        name.push(line.split(',')[1]);
        array.push([ids, name])
      });
      console.log(array);
    }

But I keep getting an error on console.log(array):

ERROR TypeError: Cannot read property 'push' of undefined

EDIT:

I changed the code into:

      let name = [];

      lines.forEach((line, index) => {
        //console.log(line);
        ids.push((line.split(',')[0]));
        name.push(line.split(',')[1]);
        array.push(ids, name)
      });
      console.log(array);

The result was like that:

enter image description here

But that's not what I need because it won't work as dataSource on material table.

13
  • Your array has no value bro. Says it right there. Commented Mar 22, 2019 at 8:14
  • I think you should assign empty array for your array like that : let array:any[]=[] Commented Mar 22, 2019 at 8:14
  • @stwilz please check my edit at the end of the question Commented Mar 22, 2019 at 8:18
  • Just for the sake of correct tags - its a pure Javascript/Typescript issue. Not related to angular or xlsx Commented Mar 22, 2019 at 8:18
  • @everyBit please check my edit at the end of the question Commented Mar 22, 2019 at 8:18

1 Answer 1

1

If I got your problem right... here is the simple way to achieve your requirement.

 let lines = ["1,xx","2,yy","3,zz"];
 let name = [];
 let array = [];
      lines.forEach((line, index) => {
        //console.log(line);
        let obj = { 
        id : line.split(',')[0],
        name : line.split(',')[1]
        };
        
        //ids.push((line.split(',')[0]));
        //name.push(line.split(',')[1]);
        array.push(obj)
      });
      
console.log(array);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.