Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

JavaScript A function that converts a two-dimensional array to CSV

Polli

New Coder
hello, please help. I need to write a function that converts a two-dimensional array to CSV format and returns a string. Valid values as array elements are numbers and strings. If a function is encountered, throw an error with the text “Unexpected value”. Example:

JavaScript:
arraysToCsv([[1, 2], ['a', 'b']]) // '1,2
a,b'
arraysToCsv([[1, 2], ['a,b', 'c,d']]) // '1,2
"a,b","c,d"'
 
hello, please help. I need to write a function that converts a two-dimensional array to CSV format and returns a string. Valid values as array elements are numbers and strings. If a function is encountered, throw an error with the text “Unexpected value”. Example:

JavaScript:
arraysToCsv([[1, 2], ['a', 'b']]) // '1,2
a,b'
arraysToCsv([[1, 2], ['a,b', 'c,d']]) // '1,2
"a,b","c,d"'
Hi there,
Did you already attempt this on your own, and get stuck somewhere?
 
Hi there,
Did you already attempt this on your own, and get stuck somewhere?
Hi! Yeh...
i tried to do it like this:
JavaScript:
function func(arr) {
return arr
    .map(array => array.map(e => {
        let type = typeof e;
        if (type !== "number" && type !== "string")
            throw new Error("Unexpected value");
        return (type === "string" && e.includes(",")) ? JSON.stringify(e) : e;
    }).join(","))
    .join("\n");
}

I did this, the test "correctly escapes quotes" fails:

JavaScript:
Expected: """"text""","other ""long"" text""
Received: ""text",other "long" text"
 

New Threads

Buy us a coffee!

Back
Top Bottom