@Kalerss

Как функцией перевести двумерный массив в CSV формат и вернуть строку?

Здравствуйте, надо написать функцию, которая переводит двумерный массив в CSV и возвращает строку.
Пример:
func([[1, 2], ['a', 'b']]) // '1,2
a,b'
func([[1, 2], ['a,b', 'c,d']]) // '1,2
"a,b","c,d"'

Сделал так, не проходит тест "корректно экранирует кавычки ":
Expected: """"text""","other ""long"" text""
Received: ""text",other "long" text"
Мой код:
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");
}

Что надо исправить?
  • Вопрос задан
  • 418 просмотров
Пригласить эксперта
Ответы на вопрос 1
Seasle
@Seasle Куратор тега JavaScript
Вам надо экранировать символы ", в том случае, если они есть в строке.
function escape(value, char = '"') {
    const preparedValue = value?.toString() ?? String(value);
    if (preparedValue.includes(char)) {
        const escapedValue = preparedValue.replaceAll(char, char.repeat(2));
        return char + escapedValue + char;
    }
    return preparedValue;
}

function toCSV(entries) {
    return entries
        .map((row) => row
            .map((entry) => {
                if (typeof entry === 'object') {
                    throw new Error('Unexpected value');
                }

                return escape(entry);
            })
            .join(',')
        )
        .join('\n');
}


console.assert(toCSV([]) === ``);
console.assert(toCSV([[]]) === ``);
console.assert(toCSV([['name', 'age']]) === `name,age`);
console.assert(toCSV([['name', 'age'], ['John', 30]]) === `name,age
John,30`);
console.assert(toCSV([[1, 2], ['a', 'b']]) === `1,2
a,b`);
console.assert(toCSV([[1, 2], ['a', 'b'], ['c', 'd']]) === `1,2
a,b
c,d`);
console.assert(toCSV([['"text"', 'other "long" text']]) === `"""text""","other ""long"" text"`);
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы