hyoseok0 / coding-test

coding test 예시 문제
0 stars 0 forks source link

[Algo] 메뉴 array를 hierarchy 를 가진 array 로 변환하세요. #4

Open hyoseok0 opened 3 years ago

hyoseok0 commented 3 years ago

interface

(a: number, b: number, c: number, d: number) => string[]

시각 format

hyoseok0 commented 3 years ago
var property = key => obj => {
    var keyArr = key.split('.')
    if (keyArr.length === 1) {
        return obj[keyArr[0]]
    }
    return property(keyArr.slice(1).join('.'))(obj[keyArr[0]])
}

var groupBy = (array, key) => {
    return array.reduce((acc, v) => {
        const groupKey = property(key)(v)
        if (acc.hasOwnProperty(groupKey)) {
            acc[groupKey].push(v)
        } else {
            acc[groupKey] = [v]   
        }
        return acc
    }, {})
}

var getParent = (array, parentId) => {
  return array.reduce((parent, item) => {
   if (item.hasOwnProperty('children')) {
      return getParent(item.children, parentId) ?? parent
   } 
   if (item._id === Number(parentId)) {
     return item
   }
   return parent
  }, undefined)
}

var solution = (array) => {
    const groupsByParentId = groupBy(array, 'parentId')
    return Object.entries(groupsByParentId).reduce((acc, [parentId, children]) => {
        const parent = getParent(array, parentId)
        if (parent) {
            parent['children'] = children
            return acc.filter(v => !children.map(childV => childV._id).includes(v._id))
        }
        return acc
    }, array)
}