Home > Mobile >  Trying to understand logic behind map method
Trying to understand logic behind map method

Time:07-06

I am trying to understand the logic of using array methods within Map functions (such as push, slice, etc). Below, I have a function that is trying to add an element in the middle of a 2D array, but it comes out completely blank. Not sure what I am missing

function array () {

let numbers = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
// Attempted outcome = [[1, 2, "Hello", 3], [4, 5, "Hello", 6], [7, 8, "Hello", 9]]

let newNumbers = numbers.map(function (row) {
  return [row.slice(2, 0, "Hello")]
})

Logger.log(newNumbers);

}

CodePudding user response:

In your script, how about the following modification?

From:

let newNumbers = numbers.map(function (row) {
  return [row.slice(2, 0, "Hello")]
})

To:

let newNumbers = numbers.map(function (row) {
  row.splice(2, 0, "Hello");
  return row;
});

or, in this case, the following modification might be able to be used.

let newNumbers = numbers.map(([a, b, ...c]) => [a, b, "Hello", ...c]);

Testing:

let numbers = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
// Attempted outcome = [[1, 2, "Hello", 3], [4, 5, "Hello", 6], [7, 8, "Hello", 9]]

let newNumbers = numbers.map(function (row) {
  row.splice(2, 0, "Hello");
  return row;
});

console.log(newNumbers);

Reference:

  • Related