0

My below code is working fine and gives the correct desired output. But I am trying to use map, filter etc. instead of for loop. Lodash map and filter also works.

var arr = [
  {"comp_id":1, desc: 'from comp1', updated: true},
{
"comp_id":2, desc: 'from comp2', updated: false}
  ];

  var complaint_sources = [
    {"comp_id":2,"consumer_source":"Hotline In","description_option":"English"},
    {"comp_id":1,"consumer_source":"Online","description_option":"Other"},
    {"comp_id":1,"consumer_source":"Email","description_option":null},
    {"comp_id":2,"consumer_source":"Email","description_option":null}]

  for(let i =0 ;i<arr.length;i++) {
    let x=[];
    for(let j=0;j<complaint_sources.length;j++){
      if(arr[i].comp_id === complaint_sources[j].comp_id){
        x.push(complaint_sources[j]);
        arr[i].comp_src = x;
      }
    }
  }
  console.log(arr);

Basically I am looping through arr array and inside that looping through the complaint_sources array and when the comp_id matches I am modifying the arr array and adding a comp_src property to the object of arr array. This comp_src property will be an array of complaint_sources matched by comp_id.

4
  • please add the desired output Commented Aug 18, 2020 at 18:47
  • 1
    Since the code works you could always try codereview.stackexchange.com Commented Aug 18, 2020 at 18:48
  • So what is your attempt at using map and filter? Commented Aug 18, 2020 at 20:33
  • Maybe it's easier to see how to do this when you move the arr[i].comp_src = x; out of the inner for loop (so that actually each arr[i] gets a .comp_src, even when it's the empty array). Commented Aug 18, 2020 at 20:36

1 Answer 1

1

this will work:

var arr = [
  {"comp_id":1, desc: 'from comp1', updated: true},
  {"comp_id":2, desc: 'from comp2', updated: false}
];

var complaint_sources = [
  {"comp_id":2,"consumer_source":"Hotline In","description_option":"English"},
  {"comp_id":1,"consumer_source":"Online","description_option":"Other"},
  {"comp_id":1,"consumer_source":"Email","description_option":null},
  {"comp_id":2,"consumer_source":"Email","description_option":null}
];
  
const grouped_sources = complaint_sources.reduce((acc, value) => {
  (acc[value.comp_id] = acc[value.comp_id] || []).push(value);
  return acc;
}, {})
  
const data = arr.map((comp) => ({
  ...comp,
  comp_src: grouped_sources[comp.comp_id]
}));

console.log(data);

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

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.