1

I am trying to concatinate dynamically generated arrays from this site https://steam.tools/itemvalue/#/wowgoldtrader-730

in my code I select and the DOM element I need dynamically let el = document.querySelectorAll('.price');

Helper function to convert the strings I get from the DOM nodes

function convert2Array() {
  return Array.prototype.slice.call(arguments);
}

For loop to iterate over each DOM element and make it into array

for(i = 0; i < el.length; i++) {
  let allPrices = []
  let arr = convert2Array(el[i].innerText);
  Array.prototype.concat.apply([], [arr])
  console.log(arr);
}

My question is, how can I produce a single array from all the arrays that are produced so I can perform calculations on that single array?

Essentially I want to get all the arrays add them up and multiply them with x

4 Answers4

0

const array1 = [1, 4, 9, 16];
const array2 = [9,10,11,12];
const singleArray = [...array1, ...array2]
const resultantArray = singleArray.map(x => x * 2);

console.log(singleArray); //merged Array
console.log(resultantArray); //array after multiplication

For producing single array from multiple array you can use spread operator

const singleArray = [...array1, ...array2, so on];

For 2nd question if I understood it correctly, you want to do some operations on that singleArray so you can use .map(), this returns a new array with operation defined in the callback function

Zain Ul Abideen
  • 1,617
  • 1
  • 11
  • 25
0

You can use the function Array.prototype.flat()

console.log([[1,2], [3, 4], [5, 6]].flat())
Ele
  • 33,468
  • 7
  • 37
  • 75
0

I'm not really sure what you are trying to achieve with the convert2Array function. What is the content of your elements with class price?

Anyway if you want an array with all the text strings just move let allprices = []; outside your for loop and then push the innertext to it.

let el = document.querySelectorAll('.price');
let allPrices = []
for(i = 0; i < el.length; i++) {
  allPrices.push(el[i].innerText);
}
console.log('allprices', allPrices)
tegner
  • 1
  • 1
0

You can use the spread operator to convert the NodeList to an array.

BUT, be careful around maths and money. JavaScript does not have a decimal number type and so usually prices need to be converted to pennies and handled with care to ensure accuracy is maintained.

const sum = (nodes) => [...nodes].reduce((acc, c) => acc + Number(c.innerHTML), 0)

const priceNodes = document.querySelectorAll('.price')

console.log(`Total cost: ${sum(priceNodes)}`)
.price, th {
    padding: 10px;
    text-align: center;
}
<table>
<tr><th></th><th>GBP</th></tr>
<tr><td>Latte</td><td class="price">1</span></tr>
<tr><td>Cappuccino</td><td class="price">2</span></tr>
</table>
Ben Aston
  • 53,718
  • 65
  • 205
  • 331