Home > OS >  with JavaScript i want to have the following output
with JavaScript i want to have the following output

Time:10-24

Output an array where a value is added to the next value of the array. The Last value will be added with the first value.

Example: [45, 4, 9, 16, 25] Converted to: [49, 13, 25, 41, 70]

Map() method must be used.

CodePudding user response:

When using Array.prototype.map() you can use the index parameter and in each iteration
to see if it's the end of the array or not like so:

const arr = [45, 4, 9, 16, 25];

const newArr = arr.map((item, i) => {
  return i !== (arr.length - 1) ? item   arr[i   1] : item   arr[0];
})

console.log(newArr);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Array.prototype.map()

CodePudding user response:

You can try following:

console.log([45, 4, 9, 16, 25].map((item, index, array) => item   array[(index   1) % array.length]))
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

This works fine.

const nums = [45, 4, 9, 16, 25];

const newNums = nums.map((item, index) => {
  if(index < nums.length - 1) {
    return item   nums[ index   1]
  }
    return item   nums[0]
})

console.log(newNums) // [ 49, 13, 25, 41, 70 ]
  • Related