diff --git a/packages/csv-stringify/lib/api/index.js b/packages/csv-stringify/lib/api/index.js index 821d096a..2c5bc4bb 100644 --- a/packages/csv-stringify/lib/api/index.js +++ b/packages/csv-stringify/lib/api/index.js @@ -113,11 +113,11 @@ const stringifier = function (options, state, info) { if (Array.isArray(chunk)) { // We are getting an array but the user has specified output columns. In // this case, we respect the columns indexes - if (columns) { - chunk.splice(columns.length); - } + const length = columns + ? Math.min(chunk.length, columns.length) + : chunk.length; // Cast record elements - for (let i = 0; i < chunk.length; i++) { + for (let i = 0; i < length; i++) { const field = chunk[i]; const [err, value] = this.__cast(field, { index: i, diff --git a/packages/csv-stringify/test/option.columns.ts b/packages/csv-stringify/test/option.columns.ts index 37bf8fd4..c6d1fd1a 100644 --- a/packages/csv-stringify/test/option.columns.ts +++ b/packages/csv-stringify/test/option.columns.ts @@ -128,6 +128,29 @@ describe("Option `columns`", function () { ); }); + it("is an array, should not be altered", function (next) { + const records = [ + ["20322051544", "1979", "8.8017226E7"], + ["28392898392", "1974", "8.8392926E7"], + ]; + stringify( + records, + { + columns: ["FIELD_1", "FIELD_2"], + }, + (err, data) => { + if (!err) { + data.should.eql("20322051544,1979\n28392898392,1974\n"); + records.should.eql([ + ["20322051544", "1979", "8.8017226E7"], + ["28392898392", "1974", "8.8392926E7"], + ]); + } + next(err); + }, + ); + }); + it("is a readable stream", function (next) { const ws = stringify( {