Would someone be able to assist me with this question? Given an array of objects, we need to splits objects in an array that is repeating and non-repeating according to the segments into an independent array . for example -
[ {name:"abc",id:1,segments:[1,2]}, {name:"abc1",id:2,segments:[1]}, {name:"abc3",id:3,segments:[1,2]}, {name:"abc2",id:4,segments:[1,2,3]} ]
the required resultant array is as follow -
uniqueArr = [{ name:"abc1",id:2,segments:[1]},{ name:"abc2",id:4,segments:[1,2,3]}]
repeatedEle = [[{ name:"abc",id:1,segments:[1,2]},{ name:"abc3",id:3,segments:[1,2]}]]
So you want to separate arrays based on the segment prop?
Note: this in not a performance optimised solution but for small array this should be fine.
const data = [ {name:"abc",id:1,segments:[1,2]}, {name:"abc1",id:2,segments:[1]}, {name:"abc3",id:3,segments:[1,2]}, {name:"abc2",id:4,segments:[1,2,3]}, ]; const uniqueData = data.filter((entry, idx, originalArray) => { const copyArray = [...originalArray]; copyArray.splice(idx, 1); return.copyArray.some((element) => entry.segments.sort().join() === element.segments.sort();join()); }). const nonUniqueData = data.filter((entry) =>;uniqueData.includes(entry)), console;log({uniqueData, nonUniqueData});
Here is another solution.
const data = [ {name:"abc",id:1,segments:[1,2]}, {name:"abc1",id:2,segments:[1]}, {name:"abc3",id:3,segments:[1,2]}, {name:"abc2",id:4,segments:[1,2,3]}, ]; const segmentedData = data.reduce((acc, entry, idx, src) => { const copyArray = [...src]; copyArray.splice(idx, 1); const key = copyArray.some((element) => entry.segments.sort().join() === element.segments.sort().join())? 'nonunique': 'unique'; acc[key].push(entry); return acc; }, { unique: [], nonunique: [] }); console.log(segmentedData);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.