I have an array of objects. These objects have two props: property 'label' of type String and a prop 'detections' which is an Array. I need a functions that can group the objects of same label merging the relative arrays.
For instance:
const list = [
{ label: 'cat', detections: ['a','b'] },
{ label: 'horse', detections: ['c','d'] },
{ label: 'cat', detections: ['e','f'] }
]
Would become:
const result = groupMergeByLabel(list)
// value logged would be => [
{ label: 'cat', detections: ['a','b','e','f'] },
{ label: 'horse', detections: ['c','d'] }
]
You could use reduce
:
const list = [ { label: 'cat', detections: ['a','b'] }, { label: 'horse', detections: ['c','d'] }, { label: 'cat', detections: ['e','f'] } ]; const result = list.reduce((res, {label, detections}) => { const existing = res.find(x => x.label === label); if (existing) { existing.detections.push(...detections); } else { res.push({label, detections}); } return res; }, []); console.log(result);
If you want the fastest method you can do that as for loops are faster than map,reduce etc.
const listA = [ { label: 'cat', detections: ['a','b'] }, { label: 'horse', detections: ['c','d'] }, { label: 'cat', detections: ['e','f'] } ] const groupMergeByLabel = (list) => { let res = []; for(let i = 0;i<list.length;i++) { const index = res.findIndex(item => item.label === list[i].label); if(index > -1) { res[index].detections = [...res[index].detections, ...list[i].detections]; } else { res.push(list[i]); } } return res; }; console.log(groupMergeByLabel(listA))
Or you can use reduce as well,
const listA = [ { label: 'cat', detections: ['a','b'] }, { label: 'horse', detections: ['c','d'] }, { label: 'cat', detections: ['e','f'] } ] const groupMergeByLabel = (list) => { const res = list.reduce((acc, curr) => { const index = acc.findIndex(item => item.label === curr.label); if(index> -1) { acc[index].detections = [...acc[index].detections, ...curr.detections]; } else { acc.push(curr); } return acc; }, []); return res; }; console.log(groupMergeByLabel(listA))
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.