Как JS кодом удалить пустые строки?
Для JS в переменной arr задан массив текста:
let arr = ["When I consider every thing that grows",
"",
"Holds in perfection but a little moment,",
"",
"That this huge stage presenteth nought but shows",
"",
"Whereon the stars in secret influence comment;"];
Как удалить из него пустые строки, и чтоб он так и остался в виде массива но только без пустых строк:

Ответы (1 шт):
Автор решения: Алексей Шиманский
→ Ссылка
C помощью filter например
let arr = ["When I consider every thing that grows",
"",
"Holds in perfection but a little moment,",
"",
"That this huge stage presenteth nought but shows",
"",
"Whereon the stars in secret influence comment;"];
let filteredArr = arr.filter(el => el.trim() !== '');
console.log(filteredArr)
через reduce
let arr = ["When I consider every thing that grows",
"",
"Holds in perfection but a little moment,",
"",
"That this huge stage presenteth nought but shows",
"",
"Whereon the stars in secret influence comment;"];
let filteredArr = arr.reduce((acc, el) => {
if (el.trim() !== '')
acc.push(el);
return acc;
}, []);
console.log(filteredArr)
Просто for..of
let arr = ["When I consider every thing that grows",
"",
"Holds in perfection but a little moment,",
"",
"That this huge stage presenteth nought but shows",
"",
"Whereon the stars in secret influence comment;"];
filteredArr = [];
for (el of arr) {
if (el.trim() !== '')
filteredArr.push(el);
}
console.log(filteredArr)
Можно изменить тот же самый массив
let arr = ["When I consider every thing that grows",
"",
"Holds in perfection but a little moment,",
"",
"That this huge stage presenteth nought but shows",
"",
"Whereon the stars in secret influence comment;"];
for (let i = arr.length - 1; i > 0; --i) {
if (arr[i].trim() === '')
arr.splice(i, 1);
}
console.log(arr)