CodeWars符号化問題2021年04月22日-Don't Drink the Water


[質問]


Don't Drink the Water
Given a two-dimensional array representation of a glass of mixed liquids, sort the array such that the liquids appear in the glass based on their density. (Lower density floats to the top) The width of the glass will not change from top to bottom.
======================

The glass representation may be larger or smaller. If a liquid doesn't fill a row, it floats to the top and to the left.
(要約)密度の低いものを前に、高いものを後ろに送ります.

[回答]

function separateLiquids(glass) {
  if(!glass.length) return [];

  const answer = [];
  const rows = glass.length;
  const columns = glass[0].length;
  const obj = {O: 0, A: 1, W: 2, H: 3};
  const obj2 = {0: 'O', 1: 'A', 2: 'W', 3: 'H'};
  const flatArr = [];

  for(let i = 0; i < rows; i++) {
    for(let j = 0; j < columns; j++) {
      flatArr.push(glass[i][j]);
    }
  }

  flatArr.map(char => obj[char])
    .sort()
    .map(n => obj2[n])
    .forEach((char, idx) => {
      if(!(idx % columns)) {
        answer.push([char]);
      }
      else {
        answer[Math.floor(idx / columns)].push(char);
      }
    })

  return answer;
}
flatを使用して一次元配列を作成しようとしたが、flatメソッドは使用できないため、1文字ずつ抽出してflatArrに保存した.
グリコ高objobj2を用いて液体の密度順に並べ替え、mapの周囲を변환 > 정렬 > 변환回転させた.
最後に2次元配列、returnに変更します.
function separateLiquids(glass) {
  if(!glass.length) return [];

  const answer = [];
  const rows = glass.length;
  const columns = glass[0].length;
  const obj = {O: 0, A: 1, W: 2, H: 3};
  const flatArr = [];

  for(let i = 0; i < rows; i++) {
    flatArr.push(...glass[i])
  }

  flatArr.sort((a, b) => {
      return obj[a] - obj[b];
    })
    .forEach((char, idx) => {
      if(!(idx % columns)) {
        answer.push([char]);
      }
      else {
        answer[Math.floor(idx / columns)].push(char);
      }
    })

  return answer;
}
もう少し包装して