• Как сортировать с приоритетом массив?

    @dimoff66
    Кратко о себе: Я есть
    С гибкими правилами

    function getSortBy(arr, rules = ['10', '110', 220]) {
      const groupedMap = arr.reduce((agg, v) => {
        if (!agg[v.groupId]) agg[v.groupId] = []
        agg[v.groupId].push(v)
        return agg
      }, {})
    
      const groups = Object
        .values(groupedMap)
        .map(arr => arr.sort((a, b) => b.source - a.source))
    
      const indexedGroups =
        groups
          .map(arr => ({ 
            arr, 
            sortIndex: (rules.indexOf(arr.map(v => v.source).join('')) + 1) || 1000
          }))
    
      const sortedGroups =
        indexedGroups.sort((a, b) => a.sortIndex - b.sortIndex)
    
      const firstGroup = sortedGroups[0].arr
      const element = firstGroup.find(v => v.source === 0)
    
      return element
    }
    
    const arr = [
      {id: 1, groupId: 100, source: 1},
     {id: 2, groupId: 100, source: 2},
     {id: 3, groupId: 100, source: 1},
     {id: 4, groupId: 200, source: 1},
     {id: 5, groupId: 200, source: 0},
     {id: 6, groupId: 300, source: 1},
     {id: 7, groupId: 300, source: 0},
     {id: 8, groupId: 300, source: 1},
     {id: 9, groupId: 400, source: 1},
     {id: 10, groupId: 400, source: 0},
     {id: 11, groupId: 400, source: 0},
     {id: 12, groupId: 500, source: 2},
     {id: 13, groupId: 500, source: 1},
    ];
    
    console.log(getSortBy(arr))  // { groupId: 200, id: 5, source: 0 }
    
    const arr2 = [
       {id: 1, groupId: 100, source: 1},
      {id: 2, groupId: 100, source: 2},
      {id: 3, groupId: 100, source: 1},
      {id: 4, groupId: 200, source: 1},
      {id: 5, groupId: 200, source: 2},
      {id: 6, groupId: 300, source: 1},
      {id: 7, groupId: 300, source: 0},
      {id: 8, groupId: 300, source: 1},
      {id: 9, groupId: 400, source: 1},
      {id: 10, groupId: 400, source: 2},
      {id: 11, groupId: 400, source: 2},
      {id: 12, groupId: 500, source: 2},
      {id: 13, groupId: 500, source: 1},
    ];
    
    console.log(getSortBy(arr2)) // { groupId: 300, id: 7, source: 0 }
    Ответ написан
    3 комментария