Home > Mobile >  How to store Array data into csv format file?
How to store Array data into csv format file?

Time:10-22

I have an array and I want to convert that array into a csv file here is my code and how i store my arrays :

const words = ['item1','item2','item3']

const txtNumber = 2;
let newArr = []

for(let t= 1 ; t <= txtNumber ; t  ) {
    const data = "item1 , item2 , item3 ,item4";
    const findWord = (word) => data.split(",").filter(x => x.includes(word))
    const array = [];
    for(let i = 0; i < words.length ; i  ) {
        const x = findWord(words[i]);
        array.push(x[0])
    }
    newArr = array.map(x => x === undefined ? '' : x.trim());
    console.log(newArr)
}

how can i store newArr values into items.csv into my pc ?

CodePudding user response:

Im a little confused about what the desired output is, so no idea if this helps.

const fs = require('fs')
let writeStream = fs.createWriteStream('output.csv')

const words = ['item1','item2','item3']

const txtNumber = 2;
let newArr = []

for(let t= 1 ; t <= txtNumber ; t  ) {
    const data = "item1 , item2 , item3 ,item4";
    const findWord = (word) => data.split(",").filter(x => x.includes(word))
    const array = [];
    for(let i = 0; i < words.length ; i  ) {
        const x = findWord(words[i]);
        array.push(x[0])
    }
    newArr = array.map(x => x === undefined ? '' : x.trim());
    //console.log(newArr)
    writeStream.write(newArr.map(x=>`"${x}"`).join(",") "\n")
}

writeStream.end()

The output of this should be (although I have not tested it)

"item1","item2","item3"
"item1","item2","item3"

CodePudding user response:

Store newArr values into items.csv

const fs = require('fs');

const words = ['item1','item2','item3']

const txtNumber = 2;
let newArr = []

for(let t= 1 ; t <= txtNumber ; t  ) {


const data = "item1 , item2 , item3 ,item4";
const findWord = (word) => data.split(",").filter(x => x.includes(word))

const array = [];
for(let i = 0; i < words.length ; i  ) {
    const x = findWord(words[i]);
    array.push(x[0])
}
newArr = array.map(x => x === undefined ? '' : x.trim());


console.log(newArr)}





const writeStream = fs.createWriteStream('items.csv');


writeStream.write(`item \n`);

writeStream.write('[ "'   newArr.join('","')   '" ]\n');

CodePudding user response:

Super lazy solution would be, for example, this NPM package found at:

https://www.npmjs.com/package/convert-array-to-csv

Disadvantage would be have an additional dependency to your project which you have no (or little) control over.

  • Related