简体   繁体   English

如何从数组 ele.nets 中删除空字符串

[英]How to remove empty strings from array elemnets

Here I am Taking a string data and converting it into array elements but it is getting an empty array at last of all array elements and I am not be able to remove them easily.Please help.在这里,我正在获取一个字符串数据并将其转换为数组元素,但它在所有数组元素的最后得到一个空数组,我无法轻松删除它们。请帮忙。

 let string_Data = `01226,Grover Cleveland,Anna,Uganda,Crucial Ltd,Tested Mutual BV,Calvin Coolidge, 77110,John F. Kennedy,hora,Bosnia Herzegovina,Formal,Papal Corporation,Franklin Roosevelt, 29552,Lyndon B. Johnson,Margaret,Palau,Summaries Holdings Inc,Customize,Rutherford B. Hayes,`; let making_Array = csv => { var data = []; for (let dataAry of csv.split('\n')) { data.push(dataAry.split(',')); } return data; } console.log(making_Array(string_Data));

Instead of manipulating arrays, you can prepare the string before being split.您可以在拆分之前准备字符串,而不是处理 arrays。

 let string_Data = `01226,Grover Cleveland,Anna,Uganda,Crucial Ltd,Tested Mutual BV,Calvin Coolidge, 77110,John F. Kennedy,hora,Bosnia Herzegovina,Formal,Papal Corporation,Franklin Roosevelt, 29552,Lyndon B. Johnson,Margaret,Palau,Summaries Holdings Inc,Customize,Rutherford B. Hayes,`; let making_Array = csv => { var data = []; for (let dataAry of csv.split('\n')) { // 1. trim both ends of the line for white space, tab, etc. // 2. remove any last trailing comma // 3. split using comma separator data.push(dataAry.trim().replace(/,$/, '').split(',')); } return data; } console.log(making_Array(string_Data));


FWIW the entire function can be streamlined, and enhanced like this: FWIW 整个 function 可以像这样精简和增强:

 let header = ['id', 'col1', 'col2', 'col3', 'col4', 'col5', 'col6']; let string_Data = `01226,Grover Cleveland,Anna,Uganda,Crucial Ltd,Tested Mutual BV,Calvin Coolidge, 77110,John F. Kennedy,hora,Bosnia Herzegovina,Formal,Papal Corporation,Franklin Roosevelt, 29552,Lyndon B. Johnson,Margaret,Palau,Summaries Holdings Inc,Customize,Rutherford B. Hayes,`; let making_Array = csv => csv.split('\n').map(line => line.trim() // 1. trim both ends of the line.replace(/,$/, '') // 2. remove any last trailing comma.split(',')) // 3. split using comma separator.map(cols => Object.fromEntries(new Map(header.map((colName, index) => [colName, cols[index] || ''])))); console.log(making_Array(string_Data));

The empty string is because of the , at the end of each line.空字符串是因为每行末尾的,

You can use the slice() method to remove the last element of the array.您可以使用slice()方法删除数组的最后一个元素。

data.push(dataAry.split(',').slice(0, -1))

When you use a negative index as the end of a slice, it counts from the end.当您使用负索引作为切片的末尾时,它从末尾开始计数。

This will remove empty strings, but it'll also remove falsey values.这将删除空字符串,但也会删除falsey值。

const values = arr.filter(Boolean);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM