Home > database >  How to empty the strings in an array of strings, but keep the length of array
How to empty the strings in an array of strings, but keep the length of array

Time:07-03

I have an array of strings in javaScript:

array = ['xx', 'xxxxxxxx', 'xxx'];

I want to reach this:

 array = ['', '', '']; //empty the strings but keep the length of array

What is the best way?

CodePudding user response:

Use Array.fill.

array = ['xx', 'xxxxxxxx', 'xxx'];
array.fill('');
console.log(array)

If you need to create a new array, use the Array constructor combined with Array.fill:

array = ['xx', 'xxxxxxxx', 'xxx'];
const newArray = new Array(array.length);
newArray.fill('');
console.log(newArray)

CodePudding user response:

use .map method to remove content and return the empty string.

array = ['xx', 'xxxxxxxx', 'xxx'];
const newArray = array.map(data=> (""));
console.log(newArray)

CodePudding user response:

array = array.map(function(item){return '';});

CodePudding user response:

Use .map() method for immutability of original array.

let array = ['xx', 'xxxxxxxx', 'xxx'];

const emptyArr = array.map((item)=>"");

console.log(emptyArr);

  • Related