I'm fairly new to coding and am trying to learn more about best practices. I wanted to have an nestedArray of objectArrays, and I wanted to be able to sort the elements in each objectArray based on matching certain property values with some in the preceding objectArray. This is what I came up with (below).
It works, but I'm not sure if there are more succinct or clearer ways of writing it. They are not intended to be grouped in alphabetical order or anything, eventually the names will be uuid's.
If you were to re-write the sortArray function using best practices, what would you change? Should it be terser?
const nestedArray =[
[ // arr 0
{ parent: "", name:"chad"}
,{ parent: "", name:"jessica"}
,{ parent: "", name:"louise"}
],
[ // arr 1
{ parent: "chad", name:"gerald"}
,{ parent: "jessica", name:"hamster" }
,{ parent: "louise", name:"billy"}
,{ parent: "louise", name:"Franklina"}
,{ parent: "chad", name:"curbiboi"}
,{ parent: "chad", name:"mnyarh"}
],
[ // arr 2
{ parent: "Franklina", name:"gerald"}
,{ parent: "mnyarh", name:"billy"}
,{ parent: "Franklina", name: "turmeric"}
]
];
console.log("---");
function sortArray(rootArray){
let newOuterArray = [rootArray[0]];
for (let i = 0; i < rootArray.length-1 ; i++){
let sortedInnerArray = []
for (let j = 0; j < rootArray[i].length ; j++){
let arrayFilteredByParentName = rootArray[i+1].filter(obj => obj.parent === rootArray[i][j].name)
arrayFilteredByParentName.forEach(element => sortedInnerArray = [...sortedInnerArray, element]);
}
newOuterArray = [...newOuterArray, sortedInnerArray];
}
return newOuterArray;
}
console.log(sortArray(nestedArray));
Here's the console output:
(3) [Array(3), Array(6), Array(3)]
0: Array(3)
0: {parent: '', name: 'chad'}
1: {parent: '', name: 'jessica'}
2: {parent: '', name: 'louise'}
length: 3
[[Prototype]]: Array(0)
1: Array(6)
0: {parent: 'chad', name: 'gerald'}
1: {parent: 'chad', name: 'curbiboi'}
2: {parent: 'chad', name: 'mnyarh'}
3: {parent: 'jessica', name: 'hamster'}
4: {parent: 'louise', name: 'billy'}
5: {parent: 'louise', name: 'Franklina'}
length: 6
[[Prototype]]: Array(0)
2: Array(3)
0: {parent: 'Franklina', name: 'gerald'}
1: {parent: 'Franklina', name: 'turmeric'}
2: {parent: 'mnyarh', name: 'billy'}
length: 3
[[Prototype]]: Array(0)
length: 3
[[Prototype]]: Array(0)