1

I'm trying to reverse and invert arrays inside a two-dimensional array.

let a = [[true, false, false], [false, true, true]];

I've made a function that takes in two-dimensional array a and does a forEach on it. This takes each inner array and reverses it. I then try to take the indivual array that was just reversed and try to do map on it to invert each value inside the array (bool => !bool).

This function seems to work up to the reverse(), but I can't figure out why the map() doesn't seem to work. Is it impossible to chain looping / iterative arrow functions like this?

var reverseInvert = a => {
  a.forEach(arr => arr.reverse().map(bool => !bool));
  return a;
};

expected result:

[[ true, true, false], [false, false, true]]

actual result:

[[false, false, true], [true, true, false]]

2 Answers 2

3

.map always creates a new array - the existing array will not be mutated. Either .map to create a new larger array:

let a = [[true, false, false], [false, true, true]];
var reverseInvert = a => {
  const newA = a.map(arr => arr.reverse().map(bool => !bool));
  return newA;
};
console.log(reverseInvert(a));

Or, if you want to mutate (not recommended unless necessary), you'll have to explicitly reassign the new mapped inner array to the index on the outer array:

let a = [[true, false, false], [false, true, true]];
var reverseInvert = a => {
  a.forEach((arr, i, outerArr) => {
    outerArr[i] = arr.reverse().map(bool => !bool)
  });
  return a;
};
console.log(reverseInvert(a));

Sign up to request clarification or add additional context in comments.

1 Comment

deleting my previous comments because I forgot to comment out my old code after I added new code in. I'm an idiot =) Thanks for the help
0

As CertainPerformance pointed out map method returns a new array and you are not assigning it:

 var reverseInvert = ([...a]) => a.reverse().map(bool => !bool);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.