3

I have an array of data, I need to make sure that the elements are sorted by nesting (parent, child) and follow each other in alphabetical order both at the top level and at the nested one.

Initial data:

const arr = [
  {
    id: 0,
    name: 'A',
    parentId: null,
  },
  {
    id: 78,
    name: 'B',
    parentId: 77,
  },
  {
    id: 1715,
    name: 'C',
    parentId: 78,
  },
  {
    id: 77,
    name: 'D',
    parentId: null,
  },
  {
    id: 1716,
    name: 'E',
    parentId: 1715,
  },
  {
    id: 76,
    name: 'F',
    parentId: null,
  },
];

My approach doesn't work because it doesn't take into account additional nesting of elements.

function sortData() {
  const result = [];

  arr.sort((a, b) => {
    return a.name.localeCompare(b.name);
  });

  for (const element of arr) {
    if (!element.parentId) {
      const children = folders.filter((el) => el.parentId === element.id);

      result.push(element, ...children);
    }
  }

  return result;
}

What data do I need to get:

const arr = [
  {
    id: 0,
    name: 'A',
    parentId: null,
  },
  {
    id: 77,
    name: 'D',
    parentId: null,
  },
  {
    id: 78,
    name: 'B',
    parentId: 77,
  },
  {
    id: 1715,
    name: 'C',
    parentId: 78,
  },
  {
    id: 1716,
    name: 'E',
    parentId: 1715,
  },
  {
    id: 76,
    name: 'F',
    parentId: null,
  },
];

What data do I get using my approach:

const arr = [
  {
    id: 0,
    name: 'A',
    parentId: null,
  },
  {
    id: 77,
    name: 'D',
    parentId: null,
  },
  {
    id: 78,
    name: 'B',
    parentId: 77,
  },
  {
    id: 76,
    name: 'F',
    parentId: null,
  }
];
Vladislav
  • 125
  • 6

2 Answers2

0

just use a simple sort function

const arr = [
  {
    id: 0,
    name: "A",
    parentId: null
  },
  {
    id: 78,
    name: "B",
    parentId: 77
  },
  {
    id: 1715,
    name: "C",
    parentId: 78
  },
  {
    id: 77,
    name: "D",
    parentId: null
  },
  {
    id: 1716,
    name: "E",
    parentId: 1715
  },
  {
    id: 76,
    name: "F",
    parentId: null
  }
];

arr.sort(function (a, b) {
if(b.parentId == a.id) return b;
  return a.id - b.id;
});

console.log('arr',arr)
João Pedro
  • 794
  • 2
  • 12
  • 28
0

It works on my side using a simple sort function

const arr = [
  {
    id: 0,
    name: 'A',
    parentId: null,
  },
  {
    id: 78,
    name: 'B',
    parentId: 77,
  },
  {
    id: 1715,
    name: 'C',
    parentId: 78,
  },
  {
    id: 77,
    name: 'D',
    parentId: null,
  },
  {
    id: 1716,
    name: 'E',
    parentId: 1715,
  },
  {
    id: 76,
    name: 'F',
    parentId: null,
  },
];

let result = []

const sortData = () => {
  arr.sort((a, b) => {
    return a.name.localeCompare(b.name);
  });
  return arr;
}

console.log(sortData())
MarkWriteCodes
  • 135
  • 1
  • 10
  • This won't work for me. Look at the item "What data do I need to get", please. Additionally, I need to sort the data by nesting (parent, child) – Vladislav Aug 11 '22 at 11:05