📜  function mutate The Array(n, a) - Javascript (1)

📅  最后修改于: 2023-12-03 15:30:52.301000             🧑  作者: Mango

Function: mutateTheArray(n, a)

The mutateTheArray function in JavaScript takes two arguments, n and a. It returns a new array of length n, where each element is the sum of the value of the corresponding element in a, its preceding element (or 0 if there isn't one), and its succeeding element (or 0 if there isn't one).

Parameters
  • n: a non-negative integer specifying the length of the new array to be returned.
  • a: an array of integers of length m.
Return Value

The mutateTheArray function returns a new array of length n.

Example Usage
const a = [4, 0, 1, -2, 3];
const n = 5;

const result = mutateTheArray(n, a);

console.log(result);
// expected output: [4, 5, -1, 2, 1]
Code Implementation
function mutateTheArray(n, a) {
  const newArray = [];

  for (let i = 0; i < n; i++) {
    let sum = 0;

    if (i > 0) {
      sum += a[i - 1];
    }

    sum += a[i];

    if (i < n - 1) {
      sum += a[i + 1];
    }

    newArray.push(sum);
  }

  return newArray;
}

The mutateTheArray function first initializes an empty array called newArray. Then, it loops through each element of the new array, calculating the sum of its value, its preceding element (if there is one), and its succeeding element (if there is one), and pushing the result to the newArray. Finally, it returns newArray.