victoriousVINAY
victoriousVINAY

Reputation: 3

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));

Upvotes: 0

Views: 947

Answers (3)

Yanick Rochon
Yanick Rochon

Reputation: 53536

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));

Upvotes: 1

Barmar
Barmar

Reputation: 781058

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.

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

When you use a negative index as the end of a slice, it counts from the end.

Upvotes: 0

chovy
chovy

Reputation: 75686

This will remove empty strings, but it'll also remove falsey values.

const values = arr.filter(Boolean);

Upvotes: 1

Related Questions