Home>

Using forEach, add the numbers with the same index number in the following two arrays
I would like to create a new array like the output items below.

const item1 = [
  '100',
  '200',
  '300',
  '400',
  '500',
]
const item2 = [
  'Ten',
  '20',
  '30',
  '40',
  '50',
]
const items = [
   '110',
   '220',
   '330',
   '440',
   '550',
]

So, I created the following code using JavaScript.

const item1 = [
  '100',
  '200',
  '300',
  '400',
  '500',
]
const item2 = [
  'Ten',
  '20',
  '30',
  '40',
  '50',
]
const items = []
item1.forEach ((item1) =>{
  item2.forEach ((item2) =>{
    let total = parseFloat (item1) + parseFloat (item2)
    items.push (total)
    console.log (total)
  })
})
110
120
130
140
150
210
220
230
240
250
310
320
330
340
350
410
420
430
440
450
510
520
530
540
550

The execution result is as above.
How can I get the output result?
Could anyone please teach me?

  • Answer # 1

    Isn't it necessary to loop twice, and add elements with the same index to form an array?

    const item1 = [
      '100',
      '200',
      '300',
      '400',
      '500',
    ]
    const item2 = [
      'Ten',
      '20',
      '30',
      '40',
      '50',
    ]
    const item = item1.map ((v, i) =>parseFloat (item2 [i]) + parseFloat (v));