首页 > 解决方案 > How to invert boolean arrays inside another array with map and forEach?

问题描述

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]]

标签: javascriptarraysecmascript-6

解决方案


.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));


推荐阅读