Brandons404
Brandons404

Reputation: 149

Is there a way to add an empty element to an array in Javascript?

I've seen posts where you use a variation of .push() .push(undefined) and .push(null) but none seem to work.. my issue might be that when I am joining the list into a string, it gets rid of the empty ones.

The ultimate goal is to iterate through an array of arrays, then for each item in a "row", remove commas from the item if it is a string, and has a comma. My code is messy, I apologize.

Due to a lot of comments I shortened the code as much as I could.. I wanted to include my .join() because I think that might be part of my issue, thanks.


    let someRow = [6, "Gaston,OH", "Brumm", "Male", , , , 2554];
    function remCommas(row) {
      let newRow = [];
      for (let item in row) {
        if (typeof row[item] === "string") {
          let Str = row[item].split();
          console.log(Str);
          let newStr = [];
          for (let char in Str) {
            if (Str[char] !== ",") {
              newStr.push(Str[char]);
            }
          }
          newRow.push(newStr.join());
        } else {
          newRow.push(row[item]);
        }
      }
      console.log(newRow);
      return newRow;
    }
    remCommas(someRow);

//          input: [6, "Gaston, OH", "Brumm", "Male", , , , 2554]
//expected output: [6, "Gaston OH", "Brumm", "Male", , , , 2554]
//  current ouput: [6, "Gaston, OH", "Brumm", "Male", 2554]

Upvotes: 1

Views: 1049

Answers (1)

Mister Jojo
Mister Jojo

Reputation: 22265

The hardest part was to understand the question, well if I understood correctly?

const input_Row = [6, "Gaston, OH", "Brumm", "Male", , , , 2554];

let output_Row = input_Row.map(row=>(typeof row==='string') ?row.replace(/,/g,'') :row)

console.log ('input_Row', input_Row)
console.log ('output_Row', output_Row)
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 2

Related Questions