Search code examples
javascriptarraysfor-of-loop

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 B.V,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));


Solution

  • Instead of manipulating arrays, you can prepare the string before being split.

    let string_Data = `01226,Grover Cleveland,Anna,Uganda,Crucial Ltd,Tested Mutual B.V,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:

    let header = ['id', 'col1', 'col2', 'col3', 'col4', 'col5', 'col6'];
    
    let string_Data = `01226,Grover Cleveland,Anna,Uganda,Crucial Ltd,Tested Mutual B.V,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));