Home > Mobile >  How to sort an array by element nesting?
How to sort an array by element nesting?

Time:08-12

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,
  }
];

CodePudding user response:

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())

CodePudding user response:

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)

  • Related