1

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'] }
]
1
  • Does it have to be in an Array? Can the overall List be in an object? Commented Dec 16, 2020 at 18:14

2 Answers 2

3

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);

Sign up to request clarification or add additional context in comments.

1 Comment

hey, idk if it's okay to ask, do you have github?
1

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))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.