Home > Back-end >  Forming new 2d array by abstract some data in the other array
Forming new 2d array by abstract some data in the other array

Time:05-26

In a scenario where I have a 2d array like this:

[
  [0,1,4,2,2,5,5,0],
  [1,1,4,4,2,2,5,3],
  [1,6,6,6,7,7,3,3],
]

And I wish to abstract the same number into a single new 2d array like the one below: {either one}

[
  [0,1],
  [1,1],
  [1,0]
]

[
  [2,2,0],
  [0,2,2]
]

[
  [0,3],
  [3,3]
]

[
  [4,0],
  [4,4]
]

[
  [5,5],
  [0,5]
]

[
  [6,6,6]
]

How can I make this kind of logic in javascript? Basically, I need to have some sort of logic to generate either one multidimensional array on the above. Just imagine getting the same number from that 2d array.

CodePudding user response:

// Initial Data
const arr = [
  [0, 1, 4, 2, 2, 5, 5, 0],
  [1, 1, 4, 4, 2, 2, 5, 3],
  [1, 6, 6, 6, 7, 7, 3, 3],
];

// Numbers you want to distribute to isolated arrays
const numbersForDistribute = [1, 2, 3, 4, 5, 6, 7];

const result = [];

for (let n of numbersForDistribute) {

  // find range within initial array for each number 
  // to determine size of result array for it 
  let minRowIndex = 999;
  let maxRowIndex = 0;

  let minColumnIndex = 999;
  let maxColumnIndex = 0;

  for (let i in arr) {
    const row = arr[i];

    for (let j in row) {
      const currentElement = row[j];

      if (row[j] === n) {
        if (i < minRowIndex) {
          minRowIndex = i;
        }

        if (i > maxRowIndex) {
          maxRowIndex = i;
        }

        if (j < minColumnIndex) {
          minColumnIndex = j;
        }

        if (j > maxColumnIndex) {
          maxColumnIndex = j;
        }
      }
    }
  }

  const resultForN = [];

  // build result array of specific size for each number 
  for (let i = minRowIndex; i <= maxRowIndex; i  ) {
    resultForN.push([]);
    for (let j = minColumnIndex; j <= maxColumnIndex; j  ) {
      resultForN[resultForN.length - 1].push(arr[i][j] === n ? n : 0);
    }
  }

  result.push(resultForN);
}

console.log(result);
.as-console-wrapper {max-height: 100% !important;top: 0;}
.as-console-row::after {display: none !important;}

  • Related