Vontar
Vontar

Reputation: 64

Creating new array out of already existing in javascript

I have an array filled with HTML objects - in my case all of them are li items. I have to create new array with textContent from these lis. So I have two arrays:

A = [li, li, li, li, li];
B = [];

I've wrote such function:

function addContent() {
  for (let i = 0; i < A.length; i++) {
    let newConent = A[i].textContent;
    B.push(newConent);
  }
}

So my question is: is there any known method or more optimal way to do that? I'm interested in JavaScript approach.

Thanks in advance (x

Upvotes: 0

Views: 122

Answers (3)

Mohammad Usman
Mohammad Usman

Reputation: 39392

You can use .map() to iterate over array of list items and return desired property values:

const list = [...document.querySelectorAll("li")];

const text = list.map(li => li.textContent);

console.log(text);
<ul class="list">
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
</ul>

Alternatively, you can also use a for...of loop:

const list = document.querySelectorAll("li");
const text = [];

for (item of list)
    text.push(item.textContent);

console.log(text);
<ul class="list">
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
</ul>

Upvotes: 1

Maheer Ali
Maheer Ali

Reputation: 36594

You can use Array.prototype.map()

The map() method creates a new array with the results of calling a provided function on every element in the calling array.

let lis = Array.from(document.querySelectorAll('li'));
let texts = lis.map(li => li.textContent);
console.log(texts);
<ul>
<li>First</li>
<li>Second</li>
<li>Third</li>
</ul>

Upvotes: 1

zmag
zmag

Reputation: 8261

If A is an array, you can do it like this:

B = A.map(li => li.textContent)

But I don't think you really have an array. If you get elements by method like querySelectorAll, you need to make an array for it.

const lis = document.querySelectorAll('li')
const A = []

for (let i = 0; i < lis.length; i++) {
  A.push(lis[i])
}

const B = A.map(li => li.textContent)

console.log(B)
<li>a</li>
<li>b</li>
<li>c</li>

Upvotes: 1

Related Questions