I have two arrays containing different types of objects. Each object in the arrays has a title assigned to it. My goal is to compare these two arrays based on their titles and move any files that are not included in the bottom part of the fileStructure
array to the end of the files
array.
const files: FileType[] = [
{
info: { name: "fileThatsNotIncludedInArray2" },
contents: [],
},
{
info: { name: "fileThatsIncludedInArray2" },
contents: [],
},
{
info: { name: "fileThatsIncluded" },
contents: [
{
info: { name: "chapterThatsNotIncludedInArray2" },
contents: [],
},
{
info: { name: "chapterThatsIncluded" },
contents: [],
},
],
},
]
Another array I'm working with is:
const filesStructure: FilesStructure[] = [
{
title: "fileThatsIncludedInArray2",
chapters: []
},
{
title: "fileThatsIncluded",
chapters:
[
{
title: "chapterThatsIncluded",
chapters: []
},
]
}
]
The desired outcome should look something like this:
const finalFiles: FileType[] = [
{
info: { name: "fileThatsIncludedInArray2" },
contents: [],
},
{
info: { name: "fileThatsIncluded" },
contents: [
{
info: { name: "chapterThatsIncluded" },
contents: [],
},
{
info: { name: "chapterThatsNotIncludedInArray2" },
contents: [],
}
],
},
{
info: { name: "fileThatsNotIncludedInArray2" },
contents: [],
},
]
Currently, my implementation only moves one item to the bottom and leaves out the rest. Here is the code snippet:
export function placeUnIncludedElementsAtTheEndOfTheSortedArray(
sortedArray: FileType[],
fileStructure: FilesStructure[],
): FileType[] {
for (const sortedFile of sortedArray) {
const findInd = fileStructure.findIndex((fr) => {
return fr.title == sortedFile.info.name
})
if (findInd == -1) {
sortedArray.push(sortedArray.splice(sortedArray.indexOf(sortedFile), 1)[0])
}
}
return sortedArray
}