1

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?

1
  • array.map(() => '') simple Commented Jul 2, 2022 at 9:56

4 Answers 4

7

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)

Sign up to request clarification or add additional context in comments.

Comments

0

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

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

Comments

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

1 Comment

Your answer could be improved by adding more information on what the code does and how it helps the OP.
0

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

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

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

console.log(emptyArr);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.