Reputation: 243
I need help in javascript. I need to remove the object which already in the path.
As you can see there are 3 paths property.
1) golang 2) Root/DCL/JAVA 3) Root/DCL/JAVA/JAVA1/JAVA2
point 2 JAVA is the root of JAVA 2 folder. I need to remove the whole object from the array.
the object can be in any position.
[
{
level: '0',
paths: 'golang',
name: 'golang',
updatedOn: 1998902546,
type: 'folder',
uuid: 'cd315c90-a9f8-48d9-9aed-a97b246b27e9',
createdOn: 1998902546,
elementType: 'folder'
},
{
level: '4', //. remove this object in an array because Root/BCL/JAVA/JAVA1/JAVA2 (JAVA2)is a child of JAVA -> Root/BCL/JAVA
paths: 'Root/BCL/JAVA/JAVA1/JAVA2',
name: 'JAVA2',
type: 'folder',
elementType: 'folder',
uuid: 'fe32e4b8-37be-4416-b129-852da83f5549',
createdOn: 2113950571
},
{
level: '2',
paths: 'Root/BCL/JAVA',
name: 'JAVA',
updatedOn: 2039112906,
type: 'folder',
elementType: 'folder',
uuid: 'cd315c90-a9f8-48d9-9aed-a97b246b27e7',
creadedOn: 2039112906
}
]
// split the paths by "/" and pushed in another array to match
for (let i = 0; i < list.length; i += 1) {
const l = parseInt(list[i].level, 10)
let splitArr = [];
if (list[i].paths.length > 0) {
splitArr = list[i].paths.split('/');
arr2.push(splitArr)
} else {
arr2.push(list[i].paths)
}
}
not sure split is required. a bit lost now, please guide.
Upvotes: 0
Views: 133
Reputation: 15268
filters on if it can find the string at position 0 of any other path.
You didn't specify what happens if paths are the same, but this will only keep the first one.
data = [
{
level: '0',
paths: 'golang',
name: 'golang',
updatedOn: 1998902546,
type: 'folder',
uuid: 'cd315c90-a9f8-48d9-9aed-a97b246b27e9',
createdOn: 1998902546,
elementType: 'folder'
},
{
level: '2',
paths: 'Root/BCL/JAVA',
name: 'JAVA',
updatedOn: 2039112906,
type: 'folder',
elementType: 'folder',
uuid: 'cd315c90-a9f8-48d9-9aed-a97b246b27e7',
createdOn: 2039112906
},
{
level: '4',
paths: 'Root/BCL/JAVA/JAVA1/JAVA2',
name: 'JAVA2',
type: 'folder',
elementType: 'folder',
uuid: 'fe32e4b8-37be-4416-b129-852da83f5549',
createdOn: 2113950571
},
{
level: '2',
paths: 'Root/BCL/JAVA',
name: 'JAVA',
updatedOn: 2039112906,
type: 'folder',
elementType: 'folder',
uuid: 'cd315c90-a9f8-48d9-9aed-a97b246b27e7',
createdOn: 2039112906
},
{
level: '4',
paths: 'Root/BCL/JAVA/JAVA1/JAVA2',
name: 'JAVA2',
type: 'folder',
elementType: 'folder',
uuid: 'x',
createdOn: 2113950571
},
{
level: '2',
paths: 'Root/BCL/JAVA',
name: 'JAVA',
updatedOn: 2039112906,
type: 'folder',
elementType: 'folder',
uuid: 'cd315c90-a9f8-48d9-9aed-a97b246b27e7',
createdOn: 2039112906
}
]
console.log(
data.filter((p,i)=>data.every((x,j)=>x===p||!p.paths.startsWith(x.paths)||(x.paths===p.paths&&i>j)))
)
Upvotes: 1